Search code examples
javaspring-bootjettyjmxembedded-jetty

How to enable and expose jmx beans programatically in jetty embedded server using spring boot?


I'm developing Spring Boot application with some REST controllers. I want to add JMX support and expose some Jetty's mbeans.

Tried to connect with jconsole but failed, so I guess JMX is disabled in this case by default.

The question is: how can I enable Jetty's JMX beans in Spring Boot application (with Jetty as embedded server).


Solution

  • I figured it out. My solution is partially based on this doc. In Spring Boot adding JMX support to Jetty is possible by adding custom server customizer. All You need to do is to add such bean:

    @Bean
    public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(@Value("${server.port:8080}") final String port) {
    
        JettyEmbeddedServletContainerFactory factory =  new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
        factory.addServerCustomizers(server -> {
            // Setup JMX
            MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
            server.addEventListener(mbContainer);
            server.addBean(mbContainer);
    
            server.addBean(Log.getLog());
    
        });
        return factory;
    }