我有一个使用 org.apache.commons.dbcp2.BasicDataSource 作为数据源 bean 的简单 Spring Boot 应用程序。
Spring boot 自动将数据源公开为 MBean。
bean 声明:
@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 配置中
关于java - 关闭 Spring Boot 应用程序时无法取消注册 DataSource JMX MBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24947717/