JMX + Spring + Commons Attributes

In my previous log4j blog I had used JMX to expose management interfaces to change log4j levels dynamically. If you look at the JBoss JMX console in that blog you will see that the parameter names are named as p1 and p2. Not very helpful. By default Spring uses reflection to expose the public methods of the MBean. Parameter names get thrown away once classes are compiled to byte code. No use of it further. Therefore there is no metadata available to print friendlier names in the JMX console.

I could use commons modeler project and externalize my MBean information completely to an XML file OR I can continue to use Spring and use Spring provided commons attribute annotations. Lets get straight to an example.

Note: The use of commons attributes is to attach metadata to classes or methods and have them available at runtime. If you are using Java 5 then commons attributes is not the best approach. Use Java 5 annotations since that is the standard now.Commons attributes is useful if you are still in JDK 1.4 world. Spring has Java 5 annotation equivalents for the same stuff described below.

This attribute compiler generates additional java classes that will hold the metadata information provided in the attribute tags in the sample code. Make sure to compile the generated source along with your normal compile.

Finally Spring must be configured to use commons attributes. Once this step is done you are in business.

I will not go into any explanations here. The AttributesJmxAttributeSource and MetadataMBeanInfoAssembler beans are the ones that configure Spring to use the commons attribute generated classes and thereby the metadata is available at runtime. Take a look at the generated attribute java source and you will quickly realize what commons-attributes is doing. By default Spring uses org.springframework.jmx.export.assembler.SimpleReflectiveMBeanInfoAssembler which uses reflection to expose all of the public methods as JMX attributes/operations. With commons-attributes you can pick and choose which methods get exposed.

The only other thing to note; In the XML configuration above I start a JMX server (from Sun). Whether you want to use Sun’s reference JMX console or use a commercial tool (or open source tool like JManage) is your choice. Similarly I chose to create my own MBeanServer. You can tag along with your containers MBean Server if you prefer.