How to correctly specify a default value in the Spring @Value annotation?

后端 未结 6 1398
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 02:57

Initially, I have the following spec:

@Value(\"#{props.isFPL}\")
private boolean isFPL=false;

This works fine correctly getting the value f

相关标签:
6条回答
  • 2020-12-15 03:25

    Try with $ as follows:

    @Value("${props.isFPL:true}")
    private boolean isFPL=false;
    

    Also make sure you set the ignore-resource-no-found to true so that if the property file is missing, the default value will be taken.

    Place the following in the context file if using XML based configuration:

    <context:property-placeholder ignore-resource-not-found="true"/>
    

    If using Java configurations:

     @Bean
     public static PropertySourcesPlaceholderConfigurer   propertySourcesPlaceholderConfigurer() {
         PropertySourcesPlaceholderConfigurer p =  new PropertySourcesPlaceholderConfigurer();
         p.setIgnoreResourceNotFound(true);
    
        return p;
     }
    
    0 讨论(0)
  • 2020-12-15 03:29

    This way of defining defaults works only if we write "value=..." in the @Value annotation. e.g.

    Does not work : @Value("${testUrl:some-url}" // This will always set "some-url" no matter what you do in the config file.

    Works : @Value(value = "${testUrl:some-url}" // This will set "some-url" only if testUrl property is missing in the config file.

    0 讨论(0)
  • 2020-12-15 03:39

    Does your Spring application context file contains more than one propertyPlaceholder beans like below:

    <context:property-placeholder ignore-resource-not-found="true" ignore-unresolvable="true" location="classpath*:/*.local.properties" />
    <context:property-placeholder location="classpath:/config.properties" />
    

    If so, then property lookup for: props.isFPL will only take place for the first property file (.local.properties), if property not found, the default value (true) will take effect and the second property file (config.properties) is effectively ignored for this property.

    0 讨论(0)
  • 2020-12-15 03:44

    For a String you can default to null like so:

    public UrlTester(@Value("${testUrl:}") String url) {
        this.url = url;
    }
    
    0 讨论(0)
  • 2020-12-15 03:44

    Depends on how you're loading your properties, if you use something like

    <context:property-placeholder location="classpath*:META-INF/spring/*.properties" />

    Then @Value should look like

    @Value("${isFPL:true}")
    
    0 讨论(0)
  • 2020-12-15 03:45

    For int type variable:

    @Value("${my.int.config: #{100}}")
    int myIntConfig;
    

    Note: there is no space before the colon, but an extra space after the colon.

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