Search code examples
javajakarta-eejndi

what is java:comp/env?


what is meant by java:comp/env ?

What does the look up like :

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

do ?

I understand that a look-up like :

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

looks up for the name MyDatasource in the context.xml or web.xml to get the URL of the database. Is it so ? !! But what does the former look up do ?


Solution

  • 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.