Spring @Configuration file with PropertyPlaceholderConfigurer bean doesn't resolve @Value annotation

后端 未结 3 822
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 14:24

I have following configuration file:

@Configuration
public class PropertyPlaceholderConfigurerConfig {

    @Value(\"${property:defaultValue}\")
    private          


        
相关标签:
3条回答
  • 2020-12-25 14:52

    If you run your application using VM option and then want to access that option in your application you have to do it slightly different:

    @Value("#{systemProperties.property}")
    private String property;
    

    Your PropertyPlaceholderConfigurer is not aware of system properties, also note that you are accessing properties using $ - which refers to place holders and # refers to beans, where systemProperties is a bean.

    0 讨论(0)
  • 2020-12-25 15:01

    For any other poor souls who couldn't get this to work in some Configuration classes when they work in others:

    Look to see what other beans you have in that class and if any of them get instantiated early in the ApplicationContext. A ConversionService is an example of one. This would instantiate the Configuration class before what is required is registered, thereby making no property injection take place.

    I fixed this by moving the ConversionService to another Configuration class that I Imported.

    0 讨论(0)
  • 2020-12-25 15:07

    From Spring JavaDoc:

    In order to resolve ${...} placeholders in definitions or @Value annotations using properties from a PropertySource, one must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using in XML, but must be explicitly registered using a static @Bean method when using @Configuration classes. See the "Working with externalized values" section of @Configuration's javadoc and "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean's javadoc for details and examples.

    So, you are trying to use a placeholder in the code block required to enable placeholder processing.

    As @M.Deinum mentioned, you should use a PropertySource (default or custom implementation).

    Example below shows how to use properties in a PropertySource annotation as well as how to inject properties from the PropertySource in a field.

    @Configuration
    @PropertySource(
              value={"classpath:properties/${property:defaultValue}.properties"},
              ignoreResourceNotFound = true)
    public class ConfigExample {
    
        @Value("${propertyNameFromFile:defaultValue}")
        String propertyToBeInjected;
    
        /**
         * Property placeholder configurer needed to process @Value annotations
         */
         @Bean
         public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
         }
    }
    
    0 讨论(0)
提交回复
热议问题