我想JdbcTemplate在Spring Boot项目中注入特定内容。我尝试按照此示例进行多种DataSource配置:http : //spring.io/blog/2014/05/27/spring- boot-1-1-0-m2-available-now
JdbcTemplate
DataSource
我的代码可以编译并运行,但是@Primary无论我@Qualifier在SqlService类中放置什么内容,都只考虑带有批注的DataSource 。我的相关代码如下:
@Primary
@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); } }
我提供了快速服务来进行尝试:
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"; } }
尝试移动@Qualifier注释到parameter你的@Bean方法JdbcTemplate。
parameter
@Bean
我想,当您将其删除时@Primary,最终会出现错误,more than one appropriate beans are presented
more than one appropriate beans are presented