@Value注解获取不到pom配置的值

本文介绍了一种在Spring框架中使用@Value注解时遇到的问题及解决方案,详细解释了为何在UrlUtil类中无法正确获取pom配置文件中的变量值,并提供了解决此问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 遇到问题:在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>详解这篇文章。











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值