Search code examples
spring-bootjmxautowiredspring-jmx

Spring Boot autowire MBean?


Spring Boot won't autowire a MBean I exported from another web application with:

@Component
@Service
@ManagedResource(objectName = IHiveService.MBEAN_NAME)
public class HiveService implements IHiveService {
    @Autowired(required = true)
    CategoryRepository categoryRepository;

    @Override
    @ManagedOperation
    public String echo(String input) {
        return "you said " + input;
    }
}

I can see and use the Bean in Oracle Java Mission Control but the other Spring Boot app is not able to autowire the bean. I this I missed an annotation. To autowire the bean I use:

@Controller
@Configuration 
@EnableMBeanExport
public class GathererControls {
   @Autowired
   IHiveService hiveService; // <-- this should be auto wired

Any ideas?


Solution

  • You don't need the @EnableMBeanExport annotation in the application where you want to access the management bean from the original application.

    What you do need is a connection to the JMX registry to get access to the exported (by the first app) management objects.

    @Configuration
    public class MyConfiguration {
    
      @Bean
      public MBeanProxyFactoryBean hiveServiceFactory() {
        MBeanProxyFactoryBean proxyFactory = new MBeanProxyFactoryBean();
        proxyFactory.setObjectName(IHiveService.MBEAN_NAME);
        proxyFactory.setProxyInterface(IHiveService.class);
        proxyFactory.afterPropertiesSet();
        return proxyFactory;
      }
    
      @Bean 
      public IHiveService hiveService(MBeanProxyFactoryBean hiveServiceFactory) {
        return (IHiveService) hiveServiceFactory.getObject();
      }
    }
    

    Now in your controller:

    @Controller
    public class GathererControls {
       @Autowired
       IHiveService hiveService; // <-- will be autowired
       // ...
       // ...
    }