2013-04-10 80 views
34

解决价值我以前曾在其他一些项目中这方面的工作,我只是重新做同样的事情,但由于某种原因,它不工作。春季@Value不是从属性文件读取,而是它的取值为字面上春天@Value不是从属性文件

AppConfig.java

@Component 
public class AppConfig 
{ 
    @Value("${key.value1}") 
    private String value; 

    public String getValue() 
    { 
     return value; 
    } 
} 

的applicationContext.xml:

<context:component-scan 
    base-package="com.test.config" /> 
<context:annotation-config /> 

<bean id="appConfigProperties" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:appconfig.properties" /> 
</bean> 

appconfig.properties

key.value1=test value 1 

在我的控制,我在那里有:

@Autowired 
private AppConfig appConfig; 

应用程序启动就好了,但是当我做

appConfig.getValue() 

返回

${key.value1} 

它不解析为属性文件中的值。

想法?

+5

Duplicated http://stackoverflow.com/questions/11890544/spring-value-annotation-in-controller-class-not-evaluating-to-value-inside-pro和http://stackoverflow.com/questions/ 5275724/spring-3-0-5-doesnt-evaluation-value-annotation-from-properties – pedjaradenkovic 2013-04-10 22:29:14

+0

谢谢!没有发现线索,最让我找到了那些被相关值为NULL – 2013-04-11 12:55:57

回答

1

有pedjaradenkovic的评论的读。

继他提供了一个链接,这是不工作的原因是@Value处理需要PropertySourcesPlaceholderConfigurer而不是PropertyPlaceholderConfigurer

+1

PropertyPlaceholderConfigurer为我的作品就好了。我只需要修复上下文:组件扫描在我的应用程序上下文中xml和spring servlet xml – 2013-04-11 12:56:38

+0

@TS请问您使用的是什么版本的spring? – Muel 2013-04-11 13:15:47

+0

Spring 3.2.2版本 – 2013-04-14 04:24:43

40

我还发现@value不工作的原因,@value需要PropertySourcesPlaceholderConfigurer代替PropertyPlaceholderConfigurer。我做了相同的更改,它对我有用,我使用的是Spring 4.0.3版本。 我这个使用下面的代码在我的配置文件进行配置 -

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
return new PropertySourcesPlaceholderConfigurer(); 
} 
+1

保存我的一天! – 2015-06-18 08:24:33

+0

谢谢。它的效果很好 – Steph 2015-11-04 10:37:54

+0

这应该被标记为正确的回应 – 2016-08-05 20:54:01

4

在我的情况下,静态字段将不会被注入。

2

我用春天启动,并为我升级版本,从1.4.0.RELEASE1.5.6.RELEASE解决了这个问题。