In this post, I describe the process to develop standalone client for ejb3 session bean hosted on JBoss -4.x application server.
Dependencies
- JBoss Client libraries
You have to import some JBoss libraries $JBOSS_HOME/client directory to the stand-alone application. These libraries are:
- jbossall-client.jar
- jboss-ejb3-client.jar
- EJB module
Add the reference of the ejb module to the application.
Getting the ejb Instance
To get the ejb instance in the client module, there are two methods:
- EJB injection
JBoss-4.x does not support EJB injection in servlets or application clients which means the annotation @EJB will not work. It’s supported on JBoss-5 version.
- JNDI lookup
For any type of ejb client (either stand-alone or web servlet), if it’s not deployed in the same ear archive of the ejb, you must set up the environment required by a JNDI application.
JNDI settings are to initialize InitialContext
object, for this, we have the below options:
- Using Application Resource Files:
- Create file named jndi.properties and save it to application class path.
- Add the following lines:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=JBOSS_IP:1099
where JBOSS_IP
is the ejb hosting JBoss server IP address and 1099 is the JBoss server JNDI port.
- Using System Properties:
How It Works
- In the IDE (here, I am using netbeans), create a new project of type Java application.
- Add the dependences mentioned above to the project libraries.
- Configure the JNDI setup using any of the two options mentioned above, here, I am using
jndi.properties
which is saved to c: drive root. - Use the
Properties
class to load the JNDI properties.
Properties props = new Properties();
props.load(new FileInputStream("c://jndi.properties"));
- Initialize the
InitialContext
instance passing the Properties
class instance to the constructor.
InitialContext ctx = new InitialContext (props);
- Use the
InitialContext
instance lookup
method to looks for the remote object inside the EJB module and return its instance.
For this, we pass the JNDI name of the remote or local interface of the session bean to lookup
method, for JBoss, the JNDI name pattern takes the following format:
EAR name / The EJB Implementation Component / remove or local
If the ejb deployed into JAR archive rather than EAR achieve, then the JNDI name pattern is:
The EJB Implementation Component / remove or local
SalaryCalc a;
a = (SalaryCalc ) ctx.lookup("SalaryCalc Bean/remote");
The code will be as follows:
try {
Properties props = new Properties();
props.load(new FileInputStream("c://jndi.properties"));
InitialContext ctx = new InitialContext(props);
SalaryCalc a = (SalaryCalc) ctx.lookup("SalaryCalc Bean/remote");
a.doaction();
} catch (IOException ex) {
System.out.println("IOException : " + ex.getMessage());
} catch (NamingException ex) {
System.out.println("NamingException : " + ex.getMessage());
}