背景
JMX
Java Coder们都知道,Java提供了JMX(Java Management Extensions) attach的机制(如JConsole),可以动态获取JVM运行时的一些信息。我们可以自定义MBean,来暴露指定的一些参数值,如DB连接数等。为方便故障排查,我们添加了一些DB相关的metrics,于是在Spring配置文件里面添加了如下代码
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false" depends-on="dataSource">
<property name="beans">
<map>
<entry key="Catalina:type=DataSource" value="#{dataSource.createPool().getJmxPool()}"/>
</map>
</property>
</bean>
MBeanExporter是Spring提供的一个工具类,可以用来注册自定义的MBean,只需要将目标类以map键值对的形式添加到beans这个属性里面。通过Jmx我们可以访问到MBean上的Public参数,从而拿到运行时的metrics。
上述是JConsole的一个截图,最后一个Tab就是由JDK默认暴露出来的一些MBean的信息。
问题描述
通过Spring的MBeanExporter注册自定义的MBean到JVM,结果工程启动报错,堆栈如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jmxExporter' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.tomcat.jdbc.pool.jmx.ConnectionPool@265c255a] with key 'Catalina:type=DataSource'; nested exception is javax.management.InstanceAlreadyExistsException: Catalina:type=DataSource
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java: