spring boot如何在ConfigurationProperties中指定多个前缀

时间:2017-06-27 01:13:39

标签: spring-boot

我必须在我的业务中使用多数据源,例如

foo.datasource.url=jdbc:mysql://127.0.0.1/foo
foo.datasource.username=root
foo.datasource.password=12345678

bar.datasource.url=jdbc:mysql://127.0.0.1/bar
...

但是有些数据源配置可以分享,例如

spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

我想知道是否可以指定多@ConfigurationProperties例如

@Bean(name = "fooDb")
@ConfigurationProperties(prefix = {"foo.datasource","spring.datasource"})
public DataSource fooDataSource() {
    return DataSourceBuilder.create().build();
}

以及如何?

1 个答案:

答案 0 :(得分:1)

毫无疑问,你不能用多个prefix来做你想做的事情。

最简单的可能就是BeanPostProcessor:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.apache.tomcat.jdbc.pool.DataSource;

@Component // or create in a configuration class
public class DataSourceCustomizer implements BeanPostProcessor {

  // .. inject here some shared properties
  // either via @Value annotation or a @ConfigurationProperties 
  // annotated class

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof DataSource) {
      // you will have to cast here to a type of your data source
      // by default it will be org.apache.tomcat.jdbc.pool.DataSource
      DataSource dataSource = (DataSource) bean;
      // .. now set some common properties ..
    }
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return bean;
  }
}