Tuesday, December 21, 2010

Exposing Spring beans as a JMX managed bean

I had a few Spring service beans that I wanted to expose as a JMX bean. I was using annotation to define my Spring beans and the steps are really straight forward to expose these as a JMX managed bean using the support from spring. Spring 2.5 and 3.0 comes shipped with some easy annotations to do this. First you define the spring exporter for managed resource.

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="autodetect" value="true"></property>
<property name="namingStrategy" ref="namingStrategy"></property>
<property name="assembler" ref="assembler"></property>
<property name="beans">
<entry key="bean:name=myManagedBean" value-ref="myService"/>

<bean id="attributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>
<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource" ref="attributeSource"/>
<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource" ref="attributeSource"/>

The exporter bean needs to have lazy-init flag set to false, this flag when set does not call the init code when the bean is loaded. The attributeSource bean indicates that we are going to use annotation to expose the bean attributes. And finally the namingStrategy bean defines how the managed beans are named and accessible in the jconsole. Once these beans are defined in the spring context now we are ready to code the managed resource.

@ManagedResource(objectName = "bean:name=myManagedBean", description = "Asample")
public class MyServiceImpl implements MyService {

private Integer myManagedAttribute;

@ManagedAttribute(description="The bean Attribute")
public void setMyManagedAttribute(Integer val){
@ManagedAttribute(description="The bean Attribute")
public Integer getMyManagedAttribute(){
return myManagedAttribute;
@ManagedOperation(description="the operation that is exposed")
public void myOperation(){

In the example which is a Spring service we can also make it a managed resources by adding the managedResource annotation the objectName given here should be the same that was given in the exporter bean key. Then every get or set method can be annotated with managedAttribute and other methods can be annotated with managedOperation.

No comments: