@Value注解取值為NULL的幾個可能原因與解決方案


在Spring MVC的架構中,如果希望在程序中直接引用properties中定義的配置值,通常是使用@Value注解的方式來獲取:

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

但是取值的時候卻可能會發現這個tagvalue的值為NULL,可能原因有:

1.使用了【static】修飾符或【final】修飾符修飾了tagValue。

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

這樣導致了tagValue的值不可改變,注解無法注入配置值。

2.在類上沒有加@Component注解(或者@service注解等)。

@Component // 必須要加上
class TestTagValue {
    @Value("${tagKey}")
    private String tagValue;
}

類上沒有相應注解不能使該類被Spring容器統一管理,注解無法注入配置值。

3.使用new關鍵字新建了一個實例,而不是使用@Autowired注解。

@Component   
class TestTagValue{
    @Value("${tagKey}")
    private String tagValue;
}

@Service
class TestService {
    // 取得到tagValue值
    @AutoWired
    private TestTagValue testTagValue;
    
    // 取不到tagValue值
    TestTagValue testTagValue1 = new TestTagValue();
}

取不到的原因和2類似,在默認的情況下交由Spring容器管理的類是單例模式的,使用new關鍵字脫離了Spring容器的管理,成員變量值沒有被注入。

 

"我走過萬千世界,最后在心底留下一片荒原。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM