我有一个简单的
Spring Boot应用程序使用org.apache.commons.dbcp2.BasicDataSource作为dataSource bean.
数据源通过Spring引导自动显示为MBean.
豆声明:
@Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(dbUrl); dataSource.setDriverClassName(jdbcDriver); dataSource.setUsername(dbUserName); dataSource.setPassword(dbPassword); return dataSource; }
一切都很好.但是,我在关闭应用程序时看到错误.此错误仅在运行可执行jar时发生.当使用Gradle Spring插件(gradle bootRun)时,没有显示.
javax.management.InstanceNotFoundException: org.apache.commons.dbcp2:name=dataSource,type=BasicDataSource at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1095) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.exclusiveUnregisterMBean(DefaultMBeanServerInterceptor.java:427) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.unregisterMBean(DefaultMBeanServerInterceptor.java:415) at com.sun.jmx.mbeanserver.JmxMBeanServer.unregisterMBean(JmxMBeanServer.java:546) at org.apache.commons.dbcp2.BasicDataSource.close(BasicDataSource.java:1822) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:350) at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:273) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:540) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:516) at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:827) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:485) at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:921) at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:895) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.doClose(EmbeddedWebApplicationContext.java:152) at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:809)
我想知道,
1.这个bean如何暴露为JMX MBean?
2.如何正确注销这个MBean?
解决方法
Spring试图关闭BasicDataSource两次:
> BasicDataSource在应用程序关闭时自动关闭
> Spring使用默认的destroy方法来关闭DataSource,但是它已经关闭了
为避免这种情况,请使用:
@Bean(destroyMethod = "") public DataSource dataSource()
在您的Java配置中