@Value使用@PropertySource注释时未解决。如何配置PropertySourcesPlaceholderConfigurer? [英] @Value not resolved when using @PropertySource annotation. How to configure PropertySourcesPlaceholderConfigurer?

查看:3822
本文介绍了@Value使用@PropertySource注释时未解决。如何配置PropertySourcesPlaceholderConfigurer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下配置类:

@Configuration
@PropertySource(name = "props", value = "classpath:/app-config.properties")
@ComponentScan("service")
public class AppConfig {

我有属性服务:

@Component 
public class SomeService {
    @Value("#{props['some.property']}") private String someProperty;

当我想使用

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String service.SomeService.someProperty; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'props' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' 

此问题已记录在 in SPR-8539

但无论如何,我无法找出如何配置 PropertySourcesPlaceholderConfigurer 以使其工作。

but anyway I cannot figure out how to configure PropertySourcesPlaceholderConfigurer to get it work.

此方法适用于xml配置

This approach works well with xml configuration

<util:properties id="props" location="classpath:/app-config.properties" />

但我想使用java进行配置。

but I want to use java for configuration.

推荐答案

如果使用@PropertySource,属性必须检索:

If you use @PropertySource, properties have to be retrieved with:

@Autowired
Environment env;
// ...
String subject = env.getProperty("mail.subject");

如果要使用@Value($ {mail.subject})检索,用xml注册prop prop占位符。

If you want to retrieve with @Value("${mail.subject}"), you have to register the prop placeholder by xml.

原因:
https://jira.springsource.org/browse/SPR-8539

这篇关于@Value使用@PropertySource注释时未解决。如何配置PropertySourcesPlaceholderConfigurer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆