Search code examples
javaspringmbeansspring-jmxmbeanexporter

Non Singleton (prototype) Spring beans JMX moniterable


I'm newbie to Spring JMX. And i want to monitor the prototype beans in my project through Spring JMX, I created a sample project to register a bean(Singleton) with Spring's MbeanExporter that is working. Then i googled to register the Non-Singleton bean with Spring JMX and monitor it but i didn't found any thing helpful.

I came across a Spring forum post that describes my problem but that answer is not to the point.


Solution

  • I kept googling for this issue and i found few posts on the stackoverlow itself that really helped me. Just copying the code here:-

     @Component("MyPrototypeScopedBeanName")
     @Scope(value = "prototype")
     @ManagedResource     
     public class MyPrototypeScopedBeanName implements SelfNaming
    
     @Autowired
     MBeanExporter exporter;
     .
     .
     @PostConstruct
     private void init() throws Exception {
        exporter.registerManagedResource(this);
     }
     .
     .
     .
    
     @Override
     public ObjectName getObjectName() throws MalformedObjectNameException {
         return new ObjectName("com.foobar", "name", this.toString());
     }
    

    Also, you may want to configure your exporter to ignore this during autodetect, because the way autodetect works with prototypes, it will create yet another instance for itself that will add an additional instance to your JMX console.

    <property name="autodetect" value="true"/>
    <!--  Done to prevent creation of additional prototype during autodetect routine -->
    <property name="excludedBeans">
        <list>
            <value>MyPrototypeScopedBeanName</value>
        </list>
    </property>
    

    Stackoverflow link

    Another link

    Courtesy:- @theJC