将 spring @value 注释评估为原始布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13585259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:33:29  来源:igfitidea点击:

Evaluating spring @value annotation as primitive boolean

springannotations

提问by 212

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

我有一个带有布尔字段的 spring @configuration 注释类 MappingsClientConfig:

 @Value("${mappings.enabled:true}")
    private boolean mappingsEnabled;

This class is imported into another spring annotated class like so :

这个类被导入到另一个 spring 注释类中,如下所示:

@Configuration
@Import(MappingsClientConfig.class)
public class LookupManagerConfig {

when instantiating the class via Spring context in a test-case the container is unable to parse the string into the boolean field mappingsEnabled and I get:

在测试用例中通过 Spring 上下文实例化类时,容器无法将字符串解析为布尔字段 mappingsEnabled,我得到:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private boolean com.barcap.tcw.mappings.economic.client.config.EconomicMappingsClientConfig.economicMappingsEnabled; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [${mappings.enabled:true}]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    ... 138 more
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [${mappings.enabled:true}]
    at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:61)
    at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:43)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:718)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    ... 140 more
Caused by: java.lang.IllegalArgumentException: Invalid boolean value [${mappings.enabled:true}]
    at org.springframework.beans.propertyeditors.CustomBooleanEditor.setAsText(CustomBooleanEditor.java:124)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:416)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:388)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:157)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:93)
    at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:49)
    ... 144 more

Any leads as to what am I missing?

关于我错过了什么的任何线索?

采纳答案by Stefan Podkowinski

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:

看起来您缺少 PropertyPlaceholderConfigurer。您需要将其注册为 bean factory 后处理器。理论上,这可以这样做:

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 bugthat causes other issues doing this from a java based configuration. See ticket for workarounds.

但是,似乎有一个错误会导致从基于 Java 的配置执行此操作的其他问题。有关变通方法,请参阅票证。

回答by realPK

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

它是一个旧线程,但如果您仍然想使用 @Value Spring 注释注入非字符串值,请执行以下操作:

@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.

在带有 Java 8 的 Spring boot 1.5.9 上对我有用。

回答by jmmut

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 @Valueis in the PipelineConfig, but the actual properties from which the option is loaded, is specified in the job class.

请注意@ValuePipelineConfig 中的 ,但加载选项的实际属性是在作业类中指定的。

回答by user3690998

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

您甚至不需要属性文件,例如:

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