Spring JMX

David Winterfeldt


JMX is good way to expose parts of your application for monitoring and management. Spring also provides support for exposing JMX for remote management (JSR-160) and creating a client to manage it. This example registers a Spring bean as a JMX MBean, exposes the JMX server over RMI, and creates a client to access it.

To connect to the example using a JMX Management tool, JConsole can be used and comes with the JDK installation. In the IDE a break point could be set in the unit test or Thread.sleep could be added to pause the application from shutting down. To activate local JMX access, the Java argument -Dcom.sun.management.jmxremote must be used when starting the test.

$ jconsole

1. Spring Configuration

The context:component-scan creates a Spring bean from the ServerManagerImpl. The context:mbean-export element will register any annotation beans as JMX MBeans.

The registry bean creates an RMI registry on the specified port. The serverConnector bean will expose JMX for remote management over RMI using the RMI registry just created.

The clientConnector creates a remote reference as an MBeanServerConnection. From this MBeanInfo can be retrieved for different JMX MBeans. But even more convenient is to create a proxy of the MBean using the MBeanProxyFactoryBean. This creates a remote proxy to the MBean specified by the p:objectName attribute, and uses the p:proxyInterface attribute to set what interface should be used for the proxy.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <context:component-scan base-package="org.springbyexample.jmx" />

    <bean id="registry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean"
          p:port="1099" />
    <!-- Expose JMX over RMI -->
    <bean id="serverConnector" class="org.springframework.jmx.support.ConnectorServerFactoryBean"
          p:serviceUrl="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/myconnector" />

    <!-- Client connector to JMX over RMI -->
    <bean id="clientConnector" class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean"
          p:serviceUrl="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/myconnector" />

    <!-- Client ServerManager proxy to JMX over RMI -->
    <bean id="serverManagerProxy" class="org.springframework.jmx.access.MBeanProxyFactoryBean"
          p:server-ref="clientConnector" />