How to read Qualifier from property file in spring boot?

Ricky picture Ricky · May 7, 2018 · Viewed 8.6k times · Source

I have a Qualifier where I read from

public class TestController{
     @Autowired
     @Qualifier("jdbc")
     private JdbcTemplate jtm;
     //.....
}

The qualifier "jdbc" is the bean defined as

@Bean(name = "jdbc")
@Autowired
public JdbcTemplate masterJdbcTemplate(@Qualifier("prod") DataSource prod) {
            return new JdbcTemplate(prod);
        }

This is the which returns the datasource for that qualifier and works fine.

Now I want to make the Qualifier name to be read from the application.properties. So I changed my code to

public class TestController{
     @Autowired
     @Qualifier("${database.connector.name}")
     private JdbcTemplate jtm;
     //.....

}

where database.connector.name=jdbc in my application.properties.

But when i do this this throws an error of

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.TestController required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your configuration.

Any help is appreciated.

Answer

Pratapi Hemant Patel picture Pratapi Hemant Patel · May 7, 2018

Qualifier doesn't resolve placeholder. You can write your TestController class as

public class TestController {

    @Value("${database.connector.name}")
    private String name;

    private JdbcTemplate jtm;

    @Autowired
    public void setJdbcTemplate(ApplicationContext context) {

        jtm = (JdbcTemplate) context.getBean(name);
    }
}