背景
今天排查一个老代码bug,最终定位到是配置文件使用@Value注解获取,实际使用时值为null。对@value进行一下用法总结
问题详细说明
我们是一个加密盐存放在application.yml中,工具类中使用如下注解获取,结果为null,大家能看出问题吗?
@Value("${md5_salt}")
private static String md5Salt;
问题就在static上,使用static修饰,会在spring初始化之前完成初始,无法注入。
错误用法总结
- 使用static或final修饰了tagValue
private static String tagValue; //错误
private final String tagValue; //错误
- 类没有加上@Component(或者@service等)
@Component //遗漏
class TestValue{
@Value("${tag}")
private String tagValue;
}
- 类被new新建了实例,而没有使用@Autowired
@Component
class TestValue{
@Value("${tag}")
private String tagValue;
}
class Test{
TestValue testValue = new TestValue()
}
本文记录了一次由于在Java代码中错误使用@Value注解导致的bug,问题在于静态变量不能被Spring正确注入配置文件中的值。作者强调了避免在静态字段上使用@Value,确保类使用@Component注解,并依赖注入而不是直接创建实例。
2174

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



