Prashant Singh
Prashant Singh

Reputation: 41

How to inject spring.datasource.* properties when DataSourceAutoConfiguration.class is excluded from autoconfiguration

I have implemented multi-tenancy in the boot application by following the below link https://dzone.com/articles/spring-boot-hibernate-multitenancy-implementation

For this I have excluded DatasourceAutoconfiguration.class from @SpringBootApplication like

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

The problem is, how do I inject properties like spring.datasource.tomcat.* to my custom datasources? To be more precise how do I set the 2 properties mentioned below to the custom datasource.

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

This is how I am setting jpa properties.

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

Upvotes: 0

Views: 602

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

You have to inject those properties into the @Configuration bean and set while creating the Tomcat Datasource manually:

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;
}

Upvotes: 1

Related Questions