原文:
翻译:石卓林 shizhuolin@hotmail.com
3.1 Resources and JNDI Naming
In a distributed application, components need to access other components and resources, such as databases. For example, a servlet might invoke remote methods on an enterprise bean that retrieves information from a database. In the Java EE platform, the Java Naming and Directory Interface (JNDI) naming service enables components to locate other components and resources.
A resource is a program object that provides connections to systems, such as database servers and messaging systems. (A Java Database Connectivity resource is sometimes referred to as a data source.) Each resource object is identified by a unique, people-friendly name, called the JNDI name. For example, the JNDI name of the preconfigured JDBC resource for the Java DB database that is shipped with the GlassFish Server is java:comp/DefaultDataSource.
An administrator creates resources in a JNDI namespace. In the GlassFish Server, you can use either the Administration Console or the asadmin command to create resources. Applications then use annotations to inject the resources. If an application uses resource injection, the GlassFish Server invokes the JNDI API, and the application is not required to do so. However, it is also possible for an application to locate resources by making direct calls to the JNDI API.
A resource object and its JNDI name are bound together by the naming and directory service. To create a new resource, a new name/object binding is entered into the JNDI namespace. You inject resources by using the @Resource annotation in an application.
You can use a deployment descriptor to override the resource mapping that you specify in an annotation. Using a deployment descriptor allows you to change an application by repackaging it rather than by both recompiling the source files and repackaging. However, for most applications, a deployment descriptor is not necessary.
3.1 资源和JNDI命名
在分布式应用中, 组件需要访问其他组件或资源, 例如数据库. 举例: 一个servlet也许会调用某企业bean上的远程方法,此方法从数据库中检索数据. 在Java EE平台中, Java命名和目录接口(JNDI)命名服务可以让组件定位其他组件或资源.
资源是一种程序对象,它可以连接到对应的系统, 例如:数据库服务器和消息系统. (Java数据库连接资源有时被称为数据源.) 每个资源被唯一的,友好的名称所标识, 这就是所谓的JNDI名. 例子: 一个为JavaDB数据库预配置的JDBC资源,其JNDI名称在GlassFish服务器上表现为java:comp/DefaultDataSource.
管理员在JNDI名称空间创建资源. 在GlassFish服务器中, 可以使用管理控制台或asadmin命令创建资源. 然后应用使用注解注射此资源. 如果应用使用资源注射, 则GlassFish服务器自行调用JNDI API, 并不需要在应用中做此操作. 当然, 也可以在应用中直接调用JNDI API定位资源.
资源对象和其名称被命名和目录服务绑定在一起. 创建新资源后, 新的名称/对象被绑定注册到JNDI命名空间. 并且在应用中使用@Resource注解注射此资源.
可以使用部署描述符覆盖注释中指定的资源映射. 使用部署描述符,您可以通过重新包装应用来改变它,而不需要重新编译源文件和重打包。当然,对于多数应用来说, 部署描述符并不是必须的.
Leave a Reply