@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 urlMaps = new HashMap();
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注入的值。

具体可参考 :详解这篇文章。











你可能感兴趣的:(Spring)