-->

春天@Value没有解决从属性文件的价值(Spring @Value is not resolvin

2019-08-21 13:32发布

我之前已经在其他一些项目中这方面的工作,我只是重新做同样的事情,但由于某种原因,它不工作。 春季@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}

它不能解决的属性文件中的值。

思考?

Answer 1:

我也找到了原因@value是不工作的, @value需要PropertySourcesPlaceholderConfigurer ,而不是一个PropertyPlaceholderConfigurer 。 我也做了同样的变化和它的工作对我来说,我使用弹簧4.0.3版本。 我这个配置使用下面的代码在我的配置文件 -

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


Answer 2:

问题是由于问题,我的applicationContext.xml VS弹簧servlet.xml中 - 这是豆子之间划定范围的问题。

pedjaradenkovic好心向我指出现有的资源: 在@Controller类春季@Value标注不评估价值里面的属性文件和春天3.0.5不评估从性能@Value注释



Answer 3:

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



Answer 4:

在我来说,我是缺少大括号。 我有@Value("foo.bar") String value ,而不是正确的形式@Value("${foo.bar}") String value



Answer 5:

对小枝引导用户都PropertyPlaceholderConfigurer和新PropertySourcesPlaceholderConfigurer在Spring 3.1中添加。 所以它的简单访问属性文件。 刚刚注入

注意:请确保您的财产不能是Static

@Value("${key.value1}")
private String value;


Answer 6:

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



Answer 7:

有pedjaradenkovic的评论的读。

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



文章来源: Spring @Value is not resolving to value from property file