在spring mvc架構中,如果希望在程序中直接使用properties中定義的配置值,通常使用一下方式來獲取:
@Value("${tag}")
private String tagValue;
但是取值時,有時這個tagvalue為NULL,可能原因有:
- 使用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()
}
這個testValue中肯定是取不到值的,必須使用@Autowired:
class Test{
@AutoWired
TestValue testValue
}
原文地址:https://blog.csdn.net/zzmlake/article/details/54946346