迁移到Tomcat 8:InstanceAlreadyExistsException数据源

Vad*_*m R 25 java configuration tomcat context.xml

我在Tomcat 8中有关于上下文配置的问题.我将项目从Tomcat 7迁移到8并且有异常问题:如果配置中没有任何更改我发现了一个错误:

    "2015-02-03 12:05:48,310 FIRST_ADMIN ERROR web.context.ContextLoader:331 
-> Context initialization failed org.springframework.jmx.export.UnableToRegisterMBeanException: 
    Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@434990dd]
     with key 'dataSource'; nested exception is 
    javax.management.InstanceAlreadyExistsException:  
    Catalina:type=DataSource,host=localhost,context=/first-
    admin,class=javax.sql.DataSource,name="jdbc/datasource/first"
Run Code Online (Sandbox Code Playgroud)

上下文的一部分:

<Resource name="jdbc/datasource/first"
              auth="Container"
              type="javax.sql.DataSource"
              poolPreparedStatements="true"
              initialSize="25"
              maxActive="100"
              maxIdle="100"
              minIdle="25"
              username="us"
              password="pa"
              driverClassName="com.mysql.jdbc.Driver"
              validationQuery="select 1"
              testOnBorrow="true"
          url="jdbc:mysql://localhost:3306/firstproject?useUnicode=true&amp;characterEncoding=UTF-8&amp;profileSQL=false&amp;autoSlowLog=false&amp;slowQueryThresholdMillis=100&amp;autoReconnect=true"/>
Run Code Online (Sandbox Code Playgroud)

所以,它在tomcat 7中运行没有任何问题.在Tomcat 8中,我可以通过两种方式解决这个问题:

  1. 通过添加到资源: singleton = "false";
  2. 通过添加到资源: factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

如果我清楚地了解tomcat为我的应用程序和jmx创建数据源,但在Tomcat 7中它是单个对象,在Tomcat 8中它必须是不同的.所以我的问题是为什么会出现这种情况?我在文档中找不到任何有关此更改的信息.我觉得更好的是:创建单个数据源(我想是这样)或者按工厂创建几个.

Rad*_*hev 12

我们遇到了同样的问题.我们将我们的数据源声明为一个spring bean,看起来spring和bean本身都试图注册一个导致这种冲突的Mbean.我们所要做的就是配置我们的Mbean Exporter,如下所示:

@Bean
public AnnotationMBeanExporter annotationMBeanExporter() {
    AnnotationMBeanExporter annotationMBeanExporter = new AnnotationMBeanExporter();
    annotationMBeanExporter.addExcludedBean("dataSource");
    return annotationMBeanExporter;
}
Run Code Online (Sandbox Code Playgroud)

虽然我认为将注册政策设置为:

annotationMBeanExporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

也可能有用.


小智 10

我有同样的错误,并通过向mbean-export部分添加registration ="ignoreExisting"来解决它:

<context:mbean-export server="mbeanServer" default-domain="mydomain" registration="ignoreExisting" />
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你想要使用注解的解决方案 Spring boot 已经定义了MBeanExporter bean,所以你可以自动连接它

@Autowired
MBeanExporter mBeanExporter ;
Run Code Online (Sandbox Code Playgroud)

然后更改注册策略

mBeanExporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);
Run Code Online (Sandbox Code Playgroud)