springboot单元测试中,@ConfigurationProperties(prefix=“xx”) 注入
今天在对写单元测试时,发现用@ConfigurationProperties(prefix=“xx”) 注入配置的类,无法获取到配置的内容,简单模拟一下:
首先是配置类,通过@ConfigurationProperties注入配置,生成两个Bean,用于标识不同的信息模块。
@Configuration
public class MsgTemplateConfig {
@Bean(name = "DAILY")
@ConfigurationProperties(prefix = "alarm.message.daily")
MsgTemplate dailyMsgTemplate() {
return new MsgTemplate();
}
@Bean(name = "ERROR")
@ConfigurationProperties(prefix = "alarm.message.error")
MsgTemplate errorMsgTemplate() {

本文探讨了在Spring Boot单元测试中,使用@ConfigurationProperties(prefix=“xx”)注解的配置类如何正确注入的问题。当在单元测试中遇到配置类属性为null的错误时,通过分析发现,配置的注入是在构造函数之后完成的。通过添加@TestPropertySource注解,成功使单元测试读取到配置文件内容,解决了问题。尽管测试通过,但背后的原理尚待进一步研究。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



