@Value not resolved when using @PropertySource annotation. How to configure PropertySourcesPlaceholderConfigurer?

前端 未结 11 1168
情深已故
情深已故 2020-11-28 23:11

I have following configuration class:

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


        
相关标签:
11条回答
  • 2020-11-28 23:47

    Don't you need a method on your @Configuration class that returns PropertySourcesPlaceholderConfigurer, annotated @Bean and is static, to register any @PropertySource with Spring?

    http://www.baeldung.com/2012/02/06/properties-with-spring/#java

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

    0 讨论(0)
  • 2020-11-28 23:50

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

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

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

    Reason: https://jira.springsource.org/browse/SPR-8539

    0 讨论(0)
  • 2020-11-28 23:56

    I had the very same problem. @PropertySource is not playing well with @Value. A quick workaround is to have an XML configuration which you'll refer to it from your Spring Java Configuration using @ImportResource as usual and that XML configuration file will include a single entry: <context:property-placeholder /> (of course with the needed namespace ceremony). Without any other change @Value will inject properties in your @Configuration pojo.

    0 讨论(0)
  • 2020-11-28 23:56

    That looks mighty complicated, can't you just do

     <context:property-placeholder location="classpath:some.properties" ignore-unresolvable="true"/>
    

    then in code reference:

    @Value("${myProperty}")
    private String myString;
    
    @Value("${myProperty.two}")
    private String myStringTwo;
    

    where some.properties looks something like this

    myProperty = whatever
    myProperty.two = something else\
    that consists of multiline string
    

    For java based config you can do this

    @Configuration
    @PropertySource(value="classpath:some.properties")
    public class SomeService {
    

    And then just inject using @value as before

    0 讨论(0)
  • 2020-11-28 23:57

    Another thing that may be happening: ensure your @Value annotated values are not static.

    0 讨论(0)
提交回复
热议问题