什么是 java: comp/env?

什么是 java:comp/env

看起来像什么:

Context envContext = (Context)initContext.lookup("java:comp/env");

做什么?

我知道这样的查询:

(DataSource)envContext.lookup("jdbc/MyDatasource")

context.xmlweb.xml中查找名称 MyDatasource以获取数据库的 URL。但是前者向上看做什么呢?

95658 次浏览

java:comp/env is the node in the JNDI tree where you can find properties for the current Java EE component (a webapp, or an EJB).

Context envContext = (Context)initContext.lookup("java:comp/env");

allows defining a variable pointing directly to this node. It allows doing

SomeBean s = (SomeBean) envContext.lookup("ejb/someBean");
DataSource ds = (DataSource) envContext.lookup("jdbc/dataSource");

rather than

SomeBean s = (SomeBean) initContext.lookup("java:comp/env/ejb/someBean");
DataSource ds = (DataSource) initContext.lookup("java:comp/env/jdbc/dataSource");

Relative paths instead of absolute paths. That's what it's used for.

It's an in-memory global hashtable where you can store global variables by name.

The "java:" url scheme causes JNDI to look for a javaURLContextFactory class, which is usually provided by your app container, e.g. here is Tomcat's implementation javadoc

See also NamingManager.getURLContext

I know I'm far late, but I was asking the same question, and I think I came some answer. So, if I may put my two cents.

java:comp/env/jdbc/myDataSource

  • java: is just like jdbc: from connection string. Acts as a protocol.
  • comp is the root for all JNDI contexts.
  • env is the subcontext for all resource related. There is another for user. Check this out.
  • jdbc is the subcontext for jdbc resources. There are types. Check the link from the previous bullet.
  • myDataSource is the name of your jdbc resource.