Evaluating spring @value annotation as primitive boolean

后端 未结 4 717
情歌与酒
情歌与酒 2020-12-05 17:47

I have a spring @configuration annotated class MappingsClientConfig with a boolean field as:

 @Value(\"${mappings.enabled:true}\")
    private boolean mappi         


        
相关标签:
4条回答
  • 2020-12-05 18:23

    This is how it was solved in our project, as the other answers didn't work for us. We were using spring batch, also.

    main job config:

    @Configuration
    @EnableBatchProcessing
    @PropertySource("classpath:application.properties")
    public class MainJobConfiguration {
        @Autowired
        PipelineConfig config;
    
        @Bean
        public PipelineConfig pipelineConfig(){
            return new PipelineConfig();
        }
    
        // To resolve ${} in @Value
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
        // job stuff ...
    }
    

    properties config loader:

    public class PipelineConfig {
        @Value("${option}")
        private boolean option;
    }
    

    Note how the @Value is in the PipelineConfig, but the actual properties from which the option is loaded, is specified in the job class.

    0 讨论(0)
  • 2020-12-05 18:42

    Looks like you're missing the PropertyPlaceholderConfigurer. You need to register it as a bean factory post processor. Theoretically this could be done like this:

    public class PostProcessorConfig {
    
        @Bean
        public BeanFactoryPostProcessor getPP() {
           PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
           configurer.setLocations(new Resource[]{new ClassPathResource("/my.properties")});
           return configurer;
        }
    }
    

    However, there seems to be a bug that causes other issues doing this from a java based configuration. See ticket for workarounds.

    0 讨论(0)
  • 2020-12-05 18:50

    Its an old thread but if you still want to inject Non-String values using @Value Spring annotation, do this:

    @Value("#{new Boolean('${item.priceFactor}')}")
    private Boolean itemFactorBoolean;
    
    @Value("#{new Integer('${item.priceFactor}')}")
    private Integer itemFactorInteger;
    

    Works for me on Spring boot 1.5.9 with Java 8.

    0 讨论(0)
  • 2020-12-05 18:50

    You even do not need a properties file, e.g.:

        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />
    

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