This article shows how to call EJB from Mbean
Let's talk about testing EJB in target environment. Assume EJB bean is ready but their clients not. It is not trivial issue to test the bean and keep whole application unchanged:
- Remote bean can be called vie RMI, but it need a client application
- Local bean can configured as remote, but it changes application. Moreover, method parameters must be Serializable
- Test client may be added to application (remote bean, JSP etc.) but it still pollutes application
Elegant solution is Mbean!
Let's start:
- First create EJB
EJB //Interface
public interface Adder {
int add(int a, int b);
}
// implementation
@Stateless
public class AdderBean implements Adder {
public int add(int a, int b) {
return a + b;
}
}
- Deploy application on Jboss
- Create Mbean
MBean Interface package adder;
import org.jboss.ejb3.annotation.Management
@Management
public interface AdderService {
int getA();
void setA(int a);
int getB();
void setB(int b);
int add();
}
Mbean Implementation package adder;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import org.jboss.ejb3.annotation.Service;
import adder.Adder;
@Service (objectName = "adder:service=AdderMbean")
public class AdderMbean implements AdderService {
private int a = 2;
private int b = 2;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public int add() {
try {
InitialContext ctx = new InitialContext();
// if AdderBean is deployed in jar instead ear,
// use ctx.lookup("AdderBean/local");
Object ref = ctx.lookup("adder-ear-1.0/AdderBean/local");
Adder adder = (Adder) PortableRemoteObject.narrow(ref,Adder.class);
return adder.add(a, b);
} catch (NamingException e) {
e.printStackTrace();
return 0;
}
}
}
- Compile and package mbean into jar
- Deploy mbean jar on Jboss
- Open JMX console (http://localhost:8080/jmx-console/), find and enjoy AdderMBean
Please note that the example is made for Jboss 5 and will not work in Jboss 4! (https://community.jboss.org/wiki/WhydontmyAS42xServicebeansdeployinAS5)
Attached adder.zip file contain example sources as Maven projects
To build ear, go to adder-ee and type mvn install. Ear is in adder-ear/target
To build mbean, go to adder-mbeans and type mvn install. Jar is in target
Comments