如何从自动配置中排除DataSourceAutoConfiguration.class时注入spring.datasource。*属性

时间:2017-09-27 07:06:35

标签: java spring hibernate spring-boot spring-data

我已按照以下链接https://dzone.com/articles/spring-boot-hibernate-multitenancy-implementation

在启动应用程序中实现了多租户

为此我从@SpringBootApplication中排除了DatasourceAutoconfiguration.class

@SpringBootApplication(
    exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableScheduling
@EnableJpaRepositories
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan("com.mps")
public class MpsServiceClientApplication {

问题是,如何将spring.datasource.tomcat.*之类的属性注入自定义数据源?更准确地说,如何将下面提到的2个属性设置为自定义数据源。

spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true

这就是我设置jpa属性的方法。

 final Map<String, Object> hibernateProps = new LinkedHashMap<>();
 hibernateProps.putAll(this.jpaProperties.getProperties());
 final LocalContainerEntityManagerFactoryBean result =
        new LocalContainerEntityManagerFactoryBean();
 result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
 result.setJpaPropertyMap(hibernateProps);

1 个答案:

答案 0 :(得分:1)

您必须将这些属性注入@Configuration bean并在手动创建Tomcat数据源时进行设置:

import org.apache.tomcat.jdbc.pool.DataSource;

@Value("${spring.datasource.test-on-borrow}")
private boolean testWhileIdle;
@Value("${spring.datasource.test-while-idle}")
private boolean testOnBorrow;

@Bean
public DataSource dataSource(){
    DataSource dataSource = new DataSource();
    dataSource.setTestOnBorrow(testOnBorrow);
    dataSource.setTestWhileIdle(testWhileIdle);
    ... 
    return dataSource;
}