Spring Boot autowire MBean?

时间:2016-09-29 13:25:03

标签: spring-boot jmx autowired spring-jmx

Spring Boot不会自动装配我从另一个Web应用程序导出的MBean:

@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;
    }
}

我可以在Oracle Java Mission Control中看到并使用Bean,但是其他Spring Boot应用程序无法自动装配bean。我这错过了一个注释。要自动装配我使用的bean:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

在您要从原始应用程序访问管理bean的应用程序中,您不需要@EnableMBeanExport注释。

您需要的是与JMX注册表的连接,以便访问导出的(通过第一个应用程序)管理对象。

@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();
  }
}

现在在您的控制器中:

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