@Value取不到值的緣由(引用application.properties中自定義的值)

在spring mvc架構中,若是但願在程序中直接使用properties中定義的配置值,一般使用一下方式來獲取:spring

@Value("${tag}")
private String tagValue;

可是取值時,有時這個tagvalue爲NULL,可能緣由有:架構

1.使用static或final修飾了tagValue,以下:

private static String tagValue; //錯誤
private final String tagValue; //錯誤

2.類沒有加上@Component(或者@service等)

@Component //遺漏
class TestValue{
    @Value("${tag}")
    private String tagValue;
}

3.類被new新建了實例,而沒有使用@Autowired

@Component 
class TestValue{
    @Value("${tag}")
    private String tagValue;
}

class Test{
    ...
    TestValue testValue = new TestValue()
}

 

正確方式: 上面這個testValue中確定是取不到值的,必須使用@Autowired

class Test{
    @AutoWired
    TestValue testValue
}
相關文章
相關標籤/搜索