MBeans

As most of the stuff in the enterprise Java world, MBeans has a cryptic name. What it does is provides a backdoor into your application.

The MBean is the class which provides those operations to expose, and the backdoor is opened by the program JConsole over JMX. JConsole is bundled along with the JDK.

As usual, this is probably easiest to explain with an example. The example uses Spring which makes the boilerplate a little easier. Using POJO isn’t much harder though, but this post won’t describe those details.

@Component
@ManagedResource
@Slf4j
public class HelloService {
    private String name = "World";

    @ManagedOperation
    public void managedHello() {
        log.info("Hello {}!", name);
    }

    @ManagedAttribute
    public String getName() {
        return name;
    }

    @ManagedAttribute
    public void setName(String name) {
        this.name = name;
    }
}

The method ‘managedHello’ can be invoked from JConsole and the attribute ‘name’ can be changed from JConsole.

This is, of course, a useless example. But it showcases the potential of MBeans.

As it turns out, Spring is already exposing the actuator operations as MBeans. You might need to put “spring.jmx.enabled=true” in your properties for it to be activated though.

A typical setup might be to expose your REST endpoints over HTTP on a port reachable by the Internet. And to expose JMX on a different port reachable from your office net. Then you can expose sensitive operations as MBeans that will only be reachable from your office.

Written on August 11, 2020

Tags: Java