Java Spring Boot 中的多个 DataSource 和 JdbcTemplate (> 1.1.0)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24755429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple DataSource and JdbcTemplate in Spring Boot (> 1.1.0)
提问by Xavier
I would like to inject a specific JdbcTemplate
in a Spring Boot project. I tried to follow this example for multiple DataSource
configuration : http://spring.io/blog/2014/05/27/spring-boot-1-1-0-m2-available-now
我想JdbcTemplate
在 Spring Boot 项目中注入一个特定的。我尝试按照此示例进行多个DataSource
配置:http: //spring.io/blog/2014/05/27/spring-boot-1-1-0-m2-available-now
My code does compile and run, but only the DataSource with the @Primary
annotation is taken into account, no matter what I put as @Qualifier
in the SqlService
class. My relevant code is the following :
我的代码确实可以编译和运行,但只考虑带有@Primary
注释的 DataSource ,无论我@Qualifier
在SqlService
类中放入什么。我的相关代码如下:
DatabaseConfig.java
:
DatabaseConfig.java
:
@Configuration
public class DatabaseConfig {
@Bean(name = "dsSlave")
@ConfigurationProperties(prefix="spring.mysql_slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dsMaster")
@Primary
@ConfigurationProperties(prefix="spring.mysql_master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "jdbcSlave")
@Autowired
@Qualifier("dsSlave")
public JdbcTemplate slaveJdbcTemplate(DataSource dsSlave) {
return new JdbcTemplate(dsSlave);
}
@Bean(name = "jdbcMaster")
@Autowired
@Qualifier("dsMaster")
public JdbcTemplate masterJdbcTemplate(DataSource dsMaster) {
return new JdbcTemplate(dsMaster);
}
}
And I did a quick service to try it out :
我做了一个快速的服务来尝试一下:
SqlService.java
:
SqlService.java
:
@Component
public class SqlService {
@Autowired
@Qualifier("jdbcSlave")
private JdbcTemplate jdbcTemplate;
public String getHelloMessage() {
String host = jdbcTemplate.queryForObject("select @@hostname;", String.class);
System.out.println(host);
return "Hello";
}
}
采纳答案by Artem Bilan
Try to move @Qualifier
annotation to the parameter
on your @Bean
methods for JdbcTemplate
.
尝试将@Qualifier
注释移动到parameter
您的@Bean
方法上的JdbcTemplate
。
I guess, when you remove @Primary
you end up with error, where more than one appropriate beans are presented
我想,当您删除时,@Primary
您最终会出错,其中more than one appropriate beans are presented
回答by KirkoR
It should looks like this:
它应该是这样的:
@Bean(name = "jdbcSlave")
@Autowired
public JdbcTemplate slaveJdbcTemplate(@Qualifier("dsSlave") DataSource dsSlave) {
return new JdbcTemplate(dsSlave);
}