Accessing an EJB from a Java Application using JNDI

It would be nice if we could use dependency injection outside of a server container. However, this is not possible from a Java SE application unless we use an embeddable container. Using an embeddable container is covered in the next recipe. Here we need to use JNDI. Accessing an EJB from a Java SE application using JNDI is similar to using JNDI in other types of applications.

Getting ready

To use this approach we need:

  1. A supporting EJB
  2. JNDI code to obtain a reference to the EJB

    We will be using the CapitalApplication developed in the Accessing an EJB from an Applet recipe found in this chapter. This recipe uses a CapitalBean to return the name of the capital given a state. Make sure the server and this application are executing before testing the Java application.

How to do it...

The EJB used here is the CapitalBean. Create a Java SE application using an IDE of your choice. It does not have to be the same one you used to develop the CapitalApplication. In the main method add:

try {
InitialContext context = new InitialContext();
String name = "java:global/CapitalApplication/CapitalBean";
CapitalBeanRemote bean = (CapitalBeanRemote)context.lookup(name);
System.out.println(bean.getCapital("India"));
}
catch(javax.naming.NoInitialContextException e) {
e.printStackTrace();
}
catch (NamingException e) {
e.printStackTrace();
}

Make sure the application's classpath contains .jar files for the CapitalBean and the appserv-rt.jar file.

When executed, the output should appear as:

New Delhi

How it works...

The application JAR file was needed to resolve the class names and the appserv-rt.jar file was needed so JNDI could function properly. This file provided the necessary information for JNDI to locate the server and look up the name correctly.

See also

The Accessing the session bean using JNDI recipe provides more detail on the use of JNDI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.3.175