Экспорт объектов Spring @Bean с использованием JMX - PullRequest
2 голосов
/ 28 июня 2010

Я использую Spring @Configuration, и заметил, что @Bean не регистрируется с использованием JMX.

Боб подключен как

@Bean
protected CountingHttpInterceptor countingHttpInterceptor() {

    return new CountingHttpInterceptor();
}

и определение класса

@ManagedResource
public class CountingHttpInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor { /* code here*/ }

Этот файл @Configuration обрабатывается после создания основного контекста приложения на основе XML и не имеет возможности принять участие в процессе обнаружения, который активируется с помощью определений XML-бинов (org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource и frieds) .

Как я могу JMX-включить бины из файла @Configuration?


Обновление : конфигурация xml

<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter">
    <property name="assembler" ref="assembler"/>
    <property name="namingStrategy" ref="namingStrategy"/>
    <property name="autodetect" value="true"/>
</bean>

<bean id="jmxAttributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>

<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
    <property name="attributeSource" ref="jmxAttributeSource"/>
</bean>

<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
    <property name="attributeSource" ref="jmxAttributeSource"/>
</bean>

Ответы [ 2 ]

4 голосов
/ 28 июня 2010

Несмотря на соблазны подхода, основанного на @Configuration, некоторые вещи остаются лучше выполненными с помощью XML-конфигурации. В частности, конфигурация на основе пространства имен, такая как <context:mbean-export>. По сути, они представляют собой «макросы», состоящие из сложных структур взаимодействующих объектов.

Теперь, вы могли бы повторить эту логику в своем классе @Configuration, но это действительно больше проблем, чем стоит. Вместо этого я предлагаю поместить такие вещи системного уровня в XML и импортировать их из вашего @Configuration класса:

@ImportResource("/path/to/beans.xml")
public class MyConfig {
   @Bean
   protected CountingHttpInterceptor countingHttpInterceptor() {
      return new CountingHttpInterceptor();
   }
}

, а затем в /path/to/beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans
           xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           ">  

    <context:mbean-export/>
</beans>
2 голосов
/ 02 августа 2014

Все, что у вас есть, правильно. В вашем классе @Configuration вы должны добавить еще одну аннотацию для экспорта ваших MBeans, @ EnableMBeanExport.

Ваш класс конфигурации будет выглядеть примерно так ...

@Configuration
@EnableMBeanExport
public class SpringConfiguration {
   @Bean
   protected CountingHttpInterceptor countingHttpInterceptor() {
      return new CountingHttpInterceptor();
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...