Over a million developers have joined DZone.

JMX and Spring - Part 2

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Hi, in my previous article I explained how to setup a JMX server through Spring and how to protect access to it through authentication and authorisation.

In this article I will show how to implement a simple MBean which allows users to change the level of a Log4j logger at runtime without the need to restart the application.

The Spring configuration has changed only slightly from my previous article to facilitate testing; the substance remains the same though.

The Spring configuration

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

    <bean id="propertyConfigurer"
        <property name="locations">

<!-- In order to automatically detect MBeans we need to recognise Spring beans -->
    <context:component-scan base-package="uk.co.jemos.experiments.jmx.mbeans" />

<!-- This causes MBeans annotations to be recognised and MBeans to be registered with the JMX server -->
    <context:mbean-export default-domain="jemos.mbeans"/>

    <bean id="jemosJmxServer" class="org.springframework.jmx.support.ConnectorServerFactoryBean"
        <property name="objectName" value="connector:name=rmi" />
        <property name="serviceUrl"
            value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector" />
        <property name="environment">
            <!-- the following is only valid when the sun jmx implementation is used -->
                <entry key="jmx.remote.x.password.file" value="${user.home}/.secure/jmxremote.password" />
                <entry key="jmx.remote.x.access.file" value="${user.home}/.secure/jmxremote.access" />

    <bean id="rmiRegistry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean">
        <property name="port" value="${jemos.jmx.rmi.port}" />

<!-- Used for testing -->
    <bean id="clientConnector" class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean"
          <property name="serviceUrl" value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector"/>
          <property name="environment">
                <entry key="jmx.remote.credentials">
                  <bean factory-method="commaDelimitedListToStringArray">
                    <constructor-arg value="${jmx.username},${jmx.password}" />


The only part of the configuration which is of interest to us is the scanning of Spring components and the declaration of the MBean exporter (which causes also MBean annotations to be recognised and Spring beans to be registered with a JMX server as MBeans)

The LoggerConfigurator MBean

package uk.co.jemos.experiments.jmx.mbeans;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

 * MBean which allows clients to change or retrieve the logging level for a
 * Log4j Logger at runtime.
 * @author mtedone
@ManagedResource(objectName = LoggerConfigurator.MBEAN_NAME, //
description = "Allows clients to set the Log4j Logger level at runtime")
public class LoggerConfigurator {
    public static final String MBEAN_NAME = "jemos.mbeans:type=config,name=LoggingConfiguration";

    @ManagedOperation(description = "Returns the Logger LEVEL for the given logger name")
    @ManagedOperationParameters({ @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"), })
    public String getLoggerLevel(String loggerName) {

        Logger logger = Logger.getLogger(loggerName);
        Level loggerLevel = logger.getLevel();

        return loggerLevel == null ? "The logger " + loggerName
                + " has not level" : loggerLevel.toString();


    @ManagedOperation(description = "Set Logger Level")
            @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"),
            @ManagedOperationParameter(description = "The Level to which the Logger must be set", name = "loggerLevel") })
    public void setLoggerLevel(String loggerName, String loggerLevel) {

        Logger thisLogger = Logger.getLogger(this.getClass());

        Logger logger = Logger.getLogger(loggerName);

        logger.setLevel(Level.toLevel(loggerLevel, Level.INFO));

        thisLogger.info("Set logger " + loggerName + " to level "
                + logger.getLevel());




Apart from Spring JMX annotations (in bold), this is a normal Spring bean. With those annotations however we have made an MBean of it and this bean will be registered with the JMX server at startup.


The @ManagedOperation and @ManagedOperationParameters annotations determine what gets displayed on the jconsole. One could omit these annotations, but the parameter names would not become something like p1 and p2, without giving any information on the type of parameter.

Invoking the function with, say, the value foo.bar.baz, INFO would result in the following output:



2011-08-11 21:33:36 LoggerConfigurator [INFO] Set logger foo.bar.baz to level INFO


In my next and last article for this series, I will show how to setup an MBean which alerts a listener when the HEAP memory threshold has been reached, as explained in one of my previous articles

Happy technology!

From http://tedone.typepad.com/blog/2011/08/jmx-and-spring-part-2.html

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}