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 JdbcTemplatein a Spring Boot project. I tried to follow this example for multiple DataSourceconfiguration : 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 @Primaryannotation is taken into account, no matter what I put as @Qualifierin the SqlServiceclass. 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 @Qualifierannotation to the parameteron your @Beanmethods for JdbcTemplate.
尝试将@Qualifier注释移动到parameter您的@Bean方法上的JdbcTemplate。
I guess, when you remove @Primaryyou 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);
}

