Required java version JDK 1.5
javax.ejb_3.0.1.jar
- create a local interface
package com.test;
import javax.ejb.Local;
@Local
public interface TestEJBLocal {
public void testMethod();
}
- Create a Remote interface
package com.test;
import javax.ejb.Remote;
@Remote
public interface TestEJBRemote {
public void testMethod();
}
We can even create Remote and Local interface in single class by adding two annotations
@Remote
@Local
- Create a Bean class
package com.test;
import javax.ejb.Stateless;
/**
* Session Bean implementation class TestEJB
*/
@Stateless(mappedName = "ejb/TestEJB")
public class TestEJB implements TestEJBRemote, TestEJBLocal {
/**
* Default constructor.
*/
public TestEJB() {
// TODO Auto-generated constructor stub
}
public void testMethod() {
System.out.println("Welcome to EJB 3.0");
}
}
EJB are component based technology to call an EJB method we need to deploy in any application server.
Create a jar then deploy in application server.
Here I’m deploying in weblogic application server.
- Client class
public class TestEJBClient {
public static void main(String [] args) {
try {
final Context context = getInitialContext();
TestEJB testEJB = (TestEJB)context.lookup("ejb/TestEJB#com.test.TestEJB");
//ejb/TestEJB is mapped name we provided in Bean then followed by the interface.
testEJB.testMethod();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static Context getInitialContext() throws NamingException {
Hashtable env = new Hashtable();
// WebLogic Server 10.x connection details
env.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
return new InitialContext( env );
}
}
Just run the main class it prints Welcome message on console