Spring @Value 未解析为属性文件中的值

新手上路,请多包涵

我以前在其他项目中做过这个,我只是重新做同样的事情,但由于某种原因它不起作用。 Spring @Value 不是从属性文件中读取,而是从字面上获取值

AppConfig.java

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

    public String getValue()
    {
        return value;
    }
}

应用上下文.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}

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

想法?

原文由 TS- 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 440
2 个回答

我还找到了原因 - @value @value PropertyPlaceholderConfigurer 的是 PropertySourcesPlaceholderConfigurer 我做了相同的更改并且对我有用,我使用的是 spring 4.0.3 版本。我在我的配置文件中使用以下代码配置了这个 -

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

原文由 Sachchidanand Singh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题