在开发过程中发现了这个问题,当我们配置druid数据源的时候是以下面的这种方式配置的
@Bean
@ConfigurationProperties("spring.datasource.druid.two")
public DataSource dataSourceTwo(){
return DruidDataSourceBuilder.create().build();
}
但是在发生 EnvironmentChangeEvent事件的时候,报出了如下错误:
Caused by: org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult: 1 errors
Field error in object 'spring.datasource.druid' on field 'url': rejected value [jdbc:mysql://XXXXXX]; codes [methodInvocation.spring.datasource.druid.url,methodInvocation.url,methodInvocation.java.lang.String,methodInvocation]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.datasource.druid.url,url]; arguments []; default message [url]]; default message [Property 'url' threw exception; nested exception is java.lang.UnsupportedOperationException]
at org.springframework.boot.bind.PropertiesConfigurationFactory.checkForBindingErrors(PropertiesConfigurationFactory.java:359)
at org.springframework.boot.bind.PropertiesConfigurationFactory.doBindPropertiesToTarget(PropertiesConfigurationFactory.java:276)
at org.springframework.boot.bind.PropertiesConfigurationFactory.bindPropertiesToTarget(PropertiesConfigurationFactory.java:240)
at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:330)
... 27 more
在https://github.com/alibaba/druid/issues/2178,有人已经提出过这个bug,但是原因讲的不是很正确
DruidDataSource初始化的时候,会将inited字段设置为true,之后就不会再执行init方法。
public void init() throws SQLException {
if (inited) { //初始化过一次之后,不会再执行
return;
}
。。。
} catch (SQLException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
} finally {
inited = true; //初始化完成之后,inited为true
lock.unlock();
if (init && LOG.isInfoEnabled()) {
LOG.info("{dataSource-" + this.getID() + "} inited");
}
}
}
Spring在设置 DruidDataSource属性的时候,比如setUrl()方法,下面的代码可以看出,如果已经初始化过,就会直接报错
public void setUrl(String jdbcUrl) {
if (inited) { // 如果已经初始化过,直接报错
throw new UnsupportedOperationException();
}
if (jdbcUrl != null) {
jdbcUrl = jdbcUrl.trim();
}
this.jdbcUrl = jdbcUrl;
// if (jdbcUrl.startsWith(ConfigFilter.URL_PREFIX)) {
// this.filters.add(new ConfigFilter());
// }
}
当我们在方法上添加@ConfigurationProperties("")注解的时候,会将bean加入到ConfigurationPropertiesRebinder的beans属性里,一旦发生EnvironmentChangeEvent事件,ConfigurationPropertiesRebinder由于监听该事件,执行onApplicationEvent方法,调用rebind,会将beans的属性重新绑定,而我们的DruidDataSource的属性是不允许修改的(上面的setUrl方法),因此会抛出UnsupportedOperationException异常,所以我们必须避免使用@ConfigurationProperties注解来初始化DruidDataSource。
DruidDataSourceBuilder.create().build()创建的是DruidDataSourceWrapper,而DruidDataSourceWrapper也是被@ConfigurationProperties所标注,因此我们也不能使用DruidDataSourceWrapper。
- druid-spring-boot-starter: 1.1.6
- spring-boot:1.5.10.RELEASE