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.
To use this approach we need:
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.
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
3.141.3.175