当前位置: 首页 > 知识库问答 >
问题:

使用@PropertySource批注时未解析@Value。如何配置PropertySourcesPlaceHolderConfigurer?

鲁旭
2023-03-14
@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' 

这种方法适用于xml配置

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

但我想使用java进行配置。

共有1个答案

蒲深
2023-03-14

如果使用@PropertySource,则必须使用以下方法检索属性:

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

如果要使用@value(“${mail.subject}”)进行检索,则必须通过XML注册合适的占位符。

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

 类似资料:
  • 问题内容: 我有以下配置类: and I have service with property: 我想使用以下命令测试AppConfig配置类时收到错误消息 该问题记录在SPR-8539中 但无论如何,我无法弄清楚如何配置PropertySourcesPlaceholderConfigurer 使其正常工作。 编辑1 这种方法适用于xml配置 但我想使用Java进行配置。 问题答案: 如果使用@P

  • 本文向大家介绍Spring @value和@PropertySource注解使用方法解析,包括了Spring @value和@PropertySource注解使用方法解析的使用技巧和注意事项,需要的朋友参考一下 这篇文章主要介绍了Spring @value和@PropertySource注解使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考

  • 我有一个打包在ear文件中的servlet,我无法让它解析@Value注释属性。 该应用程序由两部分组成:一个封装在war文件中的servlet,然后由封装在ear文件中的不同应用程序包含。该应用程序提供了由servlet中的接口定义的类(ResourceManager)的实现,以及包含@Value注释字段的属性值的属性文件。 战争文件包含: web.xml: spring-ws.xml: spr

  • 本文向大家介绍Spring @Bean注解配置及使用方法解析,包括了Spring @Bean注解配置及使用方法解析的使用技巧和注意事项,需要的朋友参考一下 使用说明 这个注解主要用在方法上,声明当前方法体中包含了最终产生 bean 实例的逻辑,方法的返回值是一个 Bean。这个 bean 会被 Spring 加入到容器中进行管理,默认情况下 bean 的命名就是使用了 bean 注解的方法名。@B

  • 问题内容: 使用诸如 可以分配具有某些属性的某些字段。 是否有更短,更简洁的形式来执行此操作? 问题答案:

  • 我正在使用@PropertySource配置一个配置类: 我现在正在使用Spring Cloud Config将配置外部化到Git:所有application.yml文件都已迁移。但是,我不知道这是否可能,以及如何将属性文件外部化,就像在@PropertySource中声明的那样。 我所做的:我尝试在Git中将mongo-prod.properties重命名为application-prod.pr