@Value註解獲取不到pom配置的值

 遇到問題:在UrlUtil類中通過@Value("${gold.url}")獲取不到pom中配置的變量值,而獲取的是變量名。文件如下:

解決辦法:在


一、獲取pom中配置的路徑方法

@Service

public class UrlUtil {

@Value("${gold.url}")
private String goldUrl;

public String getUrl(String urlType, String systemid) {
Map<String,String> urlMaps = new HashMap<String,String>();
urlMaps.put("gold_qm", goldUrl);

if (urlType!=null&&systemid!=null) {
return urlMaps.get(urlType+"_"+systemid);
}
return null;
}

}


二、pom配置gold.url 變量,局部代碼



三、使用@Value("${gold.url}")注入要在,database.properties文件中添加變量佔位,不然報如下錯誤

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.qmc.sportbetting.util.HttpHelper com.qmc.sportbetting.controller.CupRecordController.httpHelper; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpHelper': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.qmc.sportbetting.util.UrlUtil com.qmc.sportbetting.util.HttpHelper.urlUtil; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'urlUtil': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.qmc.sportbetting.util.UrlUtil.goldUrl; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'gold.url' in string value "${gold.url}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more


database.properties文件配置如下:



四、解決問題所在

    之所以在獲取不到@Value("${gold.url}")注入的值,只因爲在mvc-config.xml中配置掃描路徑時沒有添加use-default-filters="false" 可能導致所有含註解的類重複加載,因此沒獲取到值。


添加上後能正常獲取到@Value注入的值。

具體可參考 :<context:component-scan>詳解這篇文章。











發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章