Tuesday, February 22, 2011

Spring 3 & JMX

In this blog I will show you how to expose your POJOs as Managed Beans using Spring. I am assuming you are somewhat familiar with JMX, Spring, Maven, Tomcat and Java.

To expose your object as a managed bean in Tomcat, you need to register it with a MBeanServer. Spring easily allows you to do so using its config file.

Exposing your POJO as a managed bean

Here is an example of a POJO:

package com.mycompany.myapp.test;

public class TestManagedBean {

private String id;
private String name;

public String getId() {
return id;
public void setId(String id) {
this.id = id;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
Before modifying your Spring context configuration file, edit your pom.xml to include Spring jar files required for JMX.

Here is my sample pom.xml:


<!-- Spring -->

Modify your Spring context configuration file as follows. My file is called application-context.xml and is in ~myapp/src/main/resources/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.mycompany.myapp"/>

<!-- this bean must not be lazily initialized if the exporting is to happen -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<entry key="bean:name=testBean1" value-ref="testBean"/>
<property name="registrationBehaviorName" value="REGISTRATION_REPLACE_EXISTING"/>

<bean id="testBean" class="com.mycompany.myapp.test.TestManagedBean">
<property name="id" value="1"/>
<property name="name" value="Abc Def"/>


Accessing a managed bean

package com.mycompany.myapp.testjmx;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mycompany.myapp.test.TestManagedBean;

public class JmxTestClient {

public static void getMBeanServer() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
TestManagedBean service = context.getBean(TestManagedBean.class);

String name = service.getName();
System.out.println("Name = " + name);


You can now call JmxTestClient.getMBeanServer() to get access to the managed bean.

You can also use "jconsole" to view registered managed beans with Tomcat's MBeanServer. To do so, start Tomcat with "-Dcom.sun.management.jmxremote" option.
Run "jconsole" from command line. When it comes up, select and connect to "org.apache.catalina.startup.Bootstrap start" listed as a "Local Process". Click on the "MBeans" tab. You can find "jmxtest" listed under "Catalina/Manager".

No comments:

Post a Comment