SpringBoot配置两个jndi数据源

时间:2016-06-01 15:49:43

标签: spring-boot

我使用springboot来配置两个数据源 第一:

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "datasource_app")
    public DataSource appDataSource(){
            if(config.getJndiName()!=null){
        JndiDataSourceLookup dataSourceLookup = new   JndiDataSourceLookup();
        dataSourceLookup.setResourceRef(true);
        return dataSourceLookup.getDataSource(config.getJndiName());
    }
    return DataSourceBuilder.create().build();
    }

第二个

@Bean
@ConfigurationProperties(prefix = "datasource_domain")
public DataSource domainDataSource(){
    if(config.getJndiName()!=null){
        JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
        return dataSourceLookup.getDataSource(config.getJndiName());
    }
    return DataSourceBuilder.create().build();

}

但是当我运行应用程序时,我得到了这个例外:

Caused by: javax.management.InstanceAlreadyExistsException: Catalina:type=DataSource,host=localhost,context=/dir-master,class=javax.sql.DataSource,name="jdbc/dir"
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:670)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:615)
... 25 more

我做错了什么?提前致谢

1 个答案:

答案 0 :(得分:1)

默认情况下,Spring Boot将尝试向JMX注册应用程序上下文中MBean的任何bean。这导致了一个问题,因为Tomcat已经将JNDI DataSource注册为MBean。

Spring Boot自己的JndiDataSourceAutoConfiguration通过告诉应用程序上下文的MBeanExporter不导出MBean来避免这个问题:

private void excludeMBeanIfNecessary(Object candidate, String beanName) {
    try {
        MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
        if (JmxUtils.isMBean(candidate.getClass())) {
            mbeanExporter.addExcludedBean(beanName);
        }
    }
    catch (NoSuchBeanDefinitionException ex) {
        // No exporter. Exclusion is unnecessary
    }
}

您可以通过在自己的配置类中执行类似操作来避免此问题。