如何在春季启动时从属性文件读取限定符? [英] How to read Qualifier from property file in spring boot?
问题描述
我有一个限定词,我从
public class TestController{
@Autowired
@Qualifier("jdbc")
private JdbcTemplate jtm;
//.....
}
限定词"jdbc"是定义为
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.
现在,我想将限定符名称从application.properties中读取.所以我将代码更改为
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;
//.....
}
其中database.connector.name=jdbc
在我的application.properties中.
where database.connector.name=jdbc
in my application.properties.
但是当我这样做时,会引发
But when i do this this throws an error of
申请无法开始
APPLICATION FAILED TO START
说明:
main.java.rest.TestController中的字段userService需要一个Bean 键入找不到的"org.springframework.jdbc.core.JdbcTemplate".
Field userService in main.java.rest.TestController required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.
动作:
考虑在其中定义类型为"org.springframework.jdbc.core.JdbcTemplate"的bean 您的配置.
Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your configuration.
感谢您的帮助.
推荐答案
限定符不解析占位符.您可以将TestController
类写为
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);
}
}
这篇关于如何在春季启动时从属性文件读取限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!