It is very easy to use Guice’s runtime injector bindings to register MBeans on any instance of mbean server. Lets look at a simple example of a HelloMBean. In this example a simple MBean is created and registered on JBoss using google-guice runtime injection.
/**
* Hello MBean
*/
public interface HelloMBean{
public String sayHello(String name);
}
The implementation of this MBean needs to have a method for the injection of the MBeanServer.
/**
* HelloMBean implementation
*/
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.google.inject.Inject;
public class Hello implements HelloMBean{
public String sayHello(String name){
return "Hello " + name;
}
/**
* This method is used to inject an MBeanServer instance
* that will be used to register this MBean
*/
@Inject
public void register(MBeanServer server){
try {
server.registerMBean( this, new ObjectName( "Hello:type=Hello" ) );
} catch (JMException e) {
e.printStactTrace();
}
}
}
Now all that needs to be done is creating an Injector with bean and server bindings. The following piece of code can be used in any class (like a Servlet) to register the MBean when the application is deployed or as part of your injection bootstrap.
import javax.management.MBeanServer;
import org.jboss.mx.util.MBeanServerLocator;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.tools.jmx.Manager;
.
.
.
Manager.manage( "ExampleMBean", Guice.createInjector( new AbstractModule() {
@Override
protected void configure() {
// Bind the Jboss MBean server instance
bind( MBeanServer.class ).toInstance( MBeanServerLocator.locateJBoss() );
bind( HelloMBean.class ).to( Hello.class ).asEagerSingleton();
}
} ) );
You can also use “ManagementFactory.getPlatformMBeanServer()” to get/create an MBeanServer. Unfortunately this method cannot be used to get/locate the current JBoss MBeanServer, so “MBeanServerLocator” in the last code snippet above is the only way to locate a JBoss MBean Server instance. After the bean is registered you can use jboss jmx-console or jdk’s jconsole to access the mbean.