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

查看:19
本文介绍了使用 @PropertySource 注释时未解析 @Value.如何配置 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;

当我想测试 AppConfig 配置类时收到错误

I receive error when I want to test the AppConfig configuration class with

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' 

该问题在 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 placeholder.

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

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

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