Under Java EE, resources and objects can be obtained by means of a Dependency Injection. However, Dependency Injection has the following problems:
It can only be used with components managed by Java EE containers
Dependency Injection injects dependent resources and objects by means of a Java EE container. Therefore, it can be used only with components managed by Java EE containers. This is not a method that can be used with any class.
Properties coded directly into code
When Dependency Injection is used, properties are coded in annotation, and this coding is coded directly into the source. Therefore, if a property is changed, the Java source must be compiled.
The lookup can be used without taking into account the actual environment because the association between a reference name and a JNDI name can be changed using the deployment descriptor.
The above problems can be resolved by using JNDI lookup to obtain resources and objects in the conventional manner.
Various examples are shown below.
EJB Local Interface Lookup
Perform EJB local interface lookup as shown below.
Lookup Example
InitialContext ic = new InitialContext(); Calc calc = (Calc)ic.lookup("java:comp/env/Calc"); |
Example of Coding a deployment descriptor for Lookup
<ejb-local-ref> <ejb-local-ref-name>Calc</ejb-local-ref-name > <local>sample.Calc</local> <ejb-link>ejb1.jar#CalcBean</ejb-link> </ejb-local-ref > |
JMS Destination Lookup
Perform JMS Destination lookup as shown below.
Lookup Example
InitialContext ic = new InitialContext(); Queue queue = (Queue)ic.lookup("java:comp/env/jms/myQueue"); |
Example of Coding a Deployment Descriptor for Lookup
<message-destination-ref> <message-destination-ref-name>jms/myQueue</message-destination-ref-name> <message-destination-type>javax.jms.Queue</message-destination-type> <message-destination-usage>Produces</message-destination-usage> <message-destination-link>myDestination</message-destination-link> </message-destination-ref > ... <message-destination> <message-destination-name>myDestination</message-destination-name> <mapped-name>testQueue</mapped-name> </message-destination> |
JDBC Resource Lookup
Perform JDBC resource lookup as shown below.
Lookup Example
InitialContext ic = new InitialContext(); DataSource oracle = (DataSource)ic.lookup("java:comp/env/jdbc/Oracle"); |
Example of Coding a Deployment Descriptor for Lookup
<resource-ref> <res-ref-name>jdbc/Oracle</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <mapped-name>OracleTestServer</mapped-name> </resource-ref> |