天天看點

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

最近用@PropertySource直接加載配置檔案,一開始想直接加載yml,但發現他隻支援properties,于是寫了一個properties

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

先隻取其中一個format的值

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

可以看到我在構造器裡面列印了format的值,然後想着在啟動類裡面直接new一個對象,這樣就可以列印出值了

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

然後得到的結果卻讓我很失望(請忽略掉我沒有打冒号分割)

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

我覺得一定是我那裡配置錯了,各種修改取值的方式,注解等等,都沒有解決。然而容器中已經加載進了配置檔案的内容:

request.getattribute取不到值_Spring Boot中@Value取不到值的問題

最後才發現,通過@PropertySource,配置檔案被注入到Spring容器中,而自己new一個對象并不經過Spring容器,當然取不到值。AlipayService類上加了Component注解,是以正确的寫法是,通過Autowired引入bean,然後擷取屬性值。

request.getattribute取不到值_Spring Boot中@Value取不到值的問題
request.getattribute取不到值_Spring Boot中@Value取不到值的問題

鑽了個牛角尖,執着于構造器中的列印沒有值,引用了bean卻沒有用bean擷取屬性值。

果然,跳出問題本身,往往會有不一樣的發現。