我有一个预选赛,我从中阅读
public class TestController{
@Autowired
@Qualifier("jdbc")
private JdbcTemplate jtm;
//.....
}
限定符“jdbc”是定义为
的 bean@Bean(name = "jdbc")
@Autowired
public JdbcTemplate masterJdbcTemplate(@Qualifier("prod") DataSource prod) {
return new JdbcTemplate(prod);
}
这是返回该限定符的数据源并且工作正常。
现在我想从 application.properties 中读取限定符名称。所以我将代码更改为
public class TestController{
@Autowired
@Qualifier("${database.connector.name}")
private JdbcTemplate jtm;
//.....
}
其中 database.connector.name=jdbc
在我的 application.properties 中。
但是当我这样做时,会引发错误
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.
感谢任何帮助。
最佳答案
限定符无法解析占位符。您可以将您的 TestController
类编写为
public class TestController {
@Value("${database.connector.name}")
private String name;
private JdbcTemplate jtm;
@Autowired
public void setJdbcTemplate(ApplicationContext context) {
jtm = (JdbcTemplate) context.getBean(name);
}
}
关于java - 如何在Spring Boot中从属性文件中读取限定符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50208018/