我使用的是Spring boot 1.5.2版,我有一个用例,我需要在应用程序中配置2个数据源。我已经成功地将应用程序连接到2个数据库,但是我无法为它们设置连接池属性。
这是配置类:
@Configuration
public class DataSourceConfig {
@Bean(name = "oneDataSource")
@ConfigurationProperties(prefix = "spring.datasource.one")
@Primary
public DataSource oneDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "twoDataSource")
@ConfigurationProperties(prefix = "spring.datasource.two")
public DataSource twoDataSource() {
return DataSourceBuilder.create().build();
}
}
在调试DataSourceBuilder时,我可以看到它正在实例化org.apache.tomcat.jdbc.pool.DataSource类型的bean,这是我想要的,但是DataSource对象中的poolProperties字段总是包含一些默认属性而不是我的意图。
这是我的application.yml:
spring:
profiles: dev
datasource:
one:
url: jdbc:mariadb://localhost:3306/one
username: user1
password: password
driverClassName: org.mariadb.jdbc.Driver
initialize: true
tomcat:
testOnBorrow: true
validation-query: SELECT 1
testWhileIdle: true
continueOnError: true
initialSize: 2
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 5000
minIdle: 2
maxIdle: 3
maxActive: 30
two:
url: jdbc:mariadb://localhost:3306/two
username: user1
password: password
driverClassName: org.mariadb.jdbc.Driver
initialize: true
tomcat:
testOnBorrow: true
validation-query: SELECT 1
testWhileIdle: true
continueOnError: true
initialSize: 2
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 5000
minIdle: 2
maxIdle: 3
maxActive: 30
我错过了什么吗? DataSourceBuilder是否能够查找以这种方式配置的池属性?使用我想要的池属性配置2个数据源的最佳方法是什么?
答案 0 :(得分:2)
首先,您应该忽略DataSourceAutoConfiguration:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class
})
public class Main{
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
然后,将您的配置保留在您的问题中。如果您将mybatis用作DAO Framework,则应添加以下配置:
@Configuration
@MapperScan(basePackages = {"mapperpackage1"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {
@Autowired
@Qualifier("oneDataSource")
private DataSource ds1;
@Bean
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds1);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1());
return template;
}
}
同样地:
@Configuration
@MapperScan(basePackages = {"mapperpackage2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbAConfig2 {
@Autowired
@Qualifier("twoDataSource")
private DataSource ds2;
@Bean
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds2);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
return template;
}
}