Environment: JDK: 11 Spring Boot 2.5.4, Spring 5.3.9
Please excuse me, if it is an expected behaviour, or I'm doing something stupid. Consider following java based config
@Configuration
public class MyConfig
{
@Primary
@Bean("dataSource1")
@ConfigurationProperties(prefix = "app.datasource1")
public DataSource dataSource1()
{
return DataSourceBuilder.create().build();
}
@Bean("dataSource2")
@ConfigurationProperties(prefix = "app.datasource2")
public DataSource dataSource2()
{
return DataSourceBuilder.create().build();
}
@Bean
public JdbcTemplate jdbcTemplate1( DataSource dataSource1)
{
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource1);
return jdbcTemplate;
}
@Bean
public JdbcTemplate jdbcTemplate2( DataSource dataSource2)
{
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource2);
return jdbcTemplate;
}
}
and configuration file
app:
datasource1:
jdbcUrl: jdbc:postgresql://localhost:5432/postgres
driverClassname: org.postgresql.Driver
username: dbuser
password: dbpass
datasource2:
jdbcUrl: jdbc:h2:mem:2db
driverClassname: org.h2.Driver
username: SA
password:
I expect here the dataSource1 (Postgres) to be injected by name for bean jdbcTemplate1 and dataSource2 (h2) to be injected by name for bean jdbcTemplate2. In fact dataSource1 (Postgres) is being injected into both beans (I suppose since it is marked @Primary). I can resolve a problem by using method injection, calling dataSource1() and dataSource2() which works as expected and I guess is the recommended approach for java based configs, I can also add @Qualifier annotations on method parameters and this would work as well, but it not clear to me why the autowiring by name doesn't work out of the box within config. Is it a bug or a feature?
Comment From: snicoll
Autowiring by name is a fallback in case of multiple candidates with no primary. If you have further question, please follow-up on StackOverflow, as mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements.
Comment From: chpasha
No Problem, thank you - I posted it here since it looked as bug to me, but since there is a convention about Primary and fallback to resolution by name (which I was not aware of) then everything is alright