简体   繁体   中英

Registering an MBean with the JBoss MBean server - Unable to find the JBoss MBean server

I am using Spring to expose an MBean and register it with the JBoss MBean server. This works fine when the war is dropped into an instance of JBoss. It does not work however when running unit tests (which makes sense since there is no instance of JBoss running) Here is the extract from the spring configuration

<bean id="updateConfigMBean" class="mypackage.UpdateConfigMBean"/>

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server">
    <bean class="org.jboss.mx.util.MBeanServerLocator" factory-method="locateJBoss"/>
</property>
<property name="beans">
<map>
<entry key="mypackage:name=configurationMBean" value-ref="updateConfigMBean"/>
</map>
</property>
</bean>

What I am looking for is an elegant way of dealing with this issue(don't want to have two spring configurations (for testing and for deployment) and disabling the spring config validation test is not an option.

Thanks!

This is one of those situations where you are probably going to have to have two configs, one for testing and one for deployment.

This is where Maven is good, as you have a clear separation between your deployment configs and your test configs. If you are worried about keeping two configs up todate, then you need to structure your configs in such a way that all the common bits are imported into the other configs (that is how we did it).

I am using @Bean to solve that problem. @Bean is tailor-made for doing environment-specific bean creation.

The logic below is basically, in development (Tomcat) and test (JUnit), use MBeanServerFactoryBean. Otherwise use the JBoss MBean Server.

  @Bean
  def mbeanServer: MBeanServer = {
    val server = if (environment == "development" || environment == "test") {
      val factory = new MBeanServerFactoryBean
      factory.setLocateExistingServerIfPossible(true)
      factory.setRegisterWithFactory(true)
      factory.afterPropertiesSet()
      log.info("using default MBeanServer")
      factory.getObject
    } else {
      val clazz = Class.forName("org.jboss.mx.util.MBeanServerLocator")
      val locateJboss = clazz.getMethod("locateJBoss", List.empty[Class[_]].toArray: _*)
      log.info("using JBoss MBeanServer")
      locateJboss.invoke(null, 
           List.empty[java.lang.Object].toArray: _*).asInstanceOf[MBeanServer]
    }
    log.info("mbeanServer: " + server)
    server
  }

In Spring 3.1 you are able to solve this problem and still use XML configuration by using profiles. But the above works with Spring 3.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM