Spring @Value annotation not using defaults when property is not present

后端 未结 3 2208
失恋的感觉
失恋的感觉 2021-02-07 01:24

I am trying to use @Value annotation in the parameters of a constructor as follows:

@Autowired
public StringEncryptor(
    @Value(\"${encryptor.password:\\\"\\\"         


        
3条回答
  •  鱼传尺愫
    2021-02-07 01:48

    In my case, resolving the property values (and the defaults) did not work in test, where I use an annotation based configuration. It turned out that I had to add a PropertySourcesPlaceholderConfigurer so that properties actually get resolved. It was explained in the PropertySource Annotation 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 Javadoc and "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean Javadoc for details and examples.

    The following did the trick:

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    

    And if you want to add individual properties:

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    
        Properties properties = new Properties();
        properties.put("batchSize", "250");
        propertySourcesPlaceholderConfigurer.setProperties(properties);
    
        return propertySourcesPlaceholderConfigurer;
    }
    

提交回复
热议问题