JNDI(Java Naming and Directory Interface)

# 前言

 

内容基本拷贝,整理出来,方便以后回忆。

 

# What

 

The Java Naming and Directory Interface™ (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java™ programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories -new, emerging, and already deployed can be accessed in a common way.

 

The JNDI is divided into five packages:

 

 

# Why

 

J2EE 的角色

如果 Dolly 在开发应用程序时了解 J2EE 所扮演的角色,那么她就可能避免遭遇这种困境。J2EE 规范把职责委托给多个开发角色:组件提供者(Component Provider)、应用程序组装者(Application Assembler)、部署人员(Deployer)和系统管理员(System Administrator)。(在许多公司中,组件提供者和组件组装者的角色是融合在一起的,部署人员和系统管理员的角色是融合在一起的。)在真正了解 J2EE 中的 JNDI 角色之前,掌握 J2EE 角色的作用非常重要。

组件提供者

这个角色负责创建 J2EE 组件,J2EE 组件可以是 Web 应用程序、企业级 JavaBean(EJB)组件,或者是应用程序客户机(例如基于 Swing 的 GUI 客户机应用程序)。组件提供者包括:HTML 设计师、文档编程人员以及其他开发人员角色。大多数 J2EE 开发人员在组件提供者这一角色上耗费了相当多的时间。

应用程序组装者

这个角色将多个 J2EE 模块捆绑成一个彼此结合的、可以部署的整体:企业归档(EAR)文件。应用程序组装者要选择组件,分清它们之间的交互方式,配置它们的安全性和事务属性,并把应用程序打包到 EAR 文件中。许多 IDE,例如 WebSphere® Studio、IDEA、JBuilder、WebLogic Workshop 和其他 IDE,都可以帮助应用程序组装者以交互方式配置 EAR 文件。

部署人员(Deployer)

这个角色负责部署,这意味着将 EAR 安装到 J2EE 容器(应用服务器)中,然后配置资源(例如数据库连接池),把应用程序需要的资源绑定到应用服务器中的特定资源上,并启动应用程序。

系统管理员(System Administrator)

这个角色负责保证容器需要的资源可用于容器。

 

许多开发人员知道:代码和外部资源之间的紧密耦合是潜在的问题,但是在实践中却经常忘记角色的划分。在小型开发工作中(指的是团队规模或部署规模),即使忽视角色划分也能获得成功。(毕竟,如果应用程序只是个人的应用程序,而且您不准备依靠它,那么把应用程序锁定在特定的 PostgreSQL 实例上也挺好的。)

 

# How

以 Tomcat 8.5.9 为例子:

 

在项目下建立 META-INF,创建 context.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Context>
    <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" username="root" password="woaimysql-135"
    driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/onlineJudge" maxIdle="2" maxWaitMillis="5000" maxTotal="8"
    factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory">
    </Resource>
</Context>

 

在程序中:

    Context context = new InitialContext();
    Context subContext = (Context)context.lookup("java:comp/env");
    DataSource dataSource = (DataSource)subContext.lookup("jdbc/test");

 

# Reference 

https://docs.oracle.com/javase/tutorial/jndi/ Trail: Java Naming and Directory Interface

https://www.ibm.com/developerworks/cn/java/j-jndi/ JNDI 在 J2EE 中的角色

 

posted @ 2017-04-18 17:14  Piers  阅读(326)  评论(0编辑  收藏  举报