Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 600 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple DataSource and JdbcTemplate in Spring Boot (> 1.1.0)

#1
I would like to inject a specific `JdbcTemplate`in a Spring Boot project. I tried to follow this example for multiple `DataSource`configuration :

[To see links please register here]


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 :

`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`:

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

}
Reply

#2
Try to move `@Qualifier` annotation to the `parameter` on your `@Bean` methods for `JdbcTemplate`.

I guess, when you remove `@Primary` you end up with error, where `more than one appropriate beans are presented`
Reply

#3
It should looks like this:

@Bean(name = "jdbcSlave")
@Autowired
public JdbcTemplate slaveJdbcTemplate(@Qualifier("dsSlave") DataSource dsSlave) {
return new JdbcTemplate(dsSlave);
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through