spring - 使用 @PropertySource 注释时未解析 @Value。如何配置 PropertySourcesPlaceholderConfigurer?

标签 spring configuration

我有以下配置类:

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

我有属性(property)服务:

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

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

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 以使其工作。

编辑 1

这种方法适用于 xml 配置

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

但我想使用java进行配置。

最佳答案

正如@cwash 所说;

@Configuration
@PropertySource("classpath:/test-config.properties")
public class TestConfig {

     @Value("${name}")
     public String name;


     //You need this
     @Bean
     public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
     }

}

关于spring - 使用 @PropertySource 注释时未解析 @Value。如何配置 PropertySourcesPlaceholderConfigurer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13728000/

相关文章:

linux - Bash - 使用 sed 更改配置文件

java - log4j2 AsyncLogger 的内存使用情况

java - thymeleaf th :each adding coma between elements

json - Serilog.Sinks.Postgresql : Read configuration from appsettings. json

java - 使用 Spring CrudRepository 的 Hibernate LazyInitializationException

Spring Profiles 应用程序属性顺序

hadoop - java.net.ConnectException : Connection refused when trying to use hdfs 异常

tomcat - 在删除 conf/Catalina/localhost 目录之前,Tomcat6 中所有应用程序中的 404

java - Spring构造函数注入(inject)和 super 调用冗长

java - Spring Security CORS 过滤器不起作用