2017-06-27 14 views
1

私は自分のビジネスでマルチデータソースを使用する必要があります。SpringブートでConfigurationPropertiesのマルチプレフィックスを指定する方法

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

多分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; 
    } 
} 
関連する問題