Java – how to correctly specify the default value in the spring @ value annotation?

Initially, I had the following specifications:

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

This will correctly get the value from the properties file:

isFPL = true

However, by default, the following expression causes an error:

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

Expression parsing failed; The nested exception is org springframework. expression. spel. Spelparseexception: el1041e: (POS 28): after parsing a valid expression, there is more data in the expression: 'colon (:)'

I also tried to use $instead of #

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

Then the default value in the comment works normally, but the correct value is not obtained from the properties file:

Solution

Try $as follows

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

Also ensure that ignore - resource - no - found is set to true so that if the properties file is missing, the default value will be used

In addition, place the following in –

Context file if XM based configuration is used:

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

In the configuration class, if Java configuration is used:

@Bean
 public static PropertySourcesPlaceholderConfigurer   propertySourcesPlaceholderConfigurer() {
     PropertySourcesPlaceholderConfigurer p =  new PropertySourcesPlaceholderConfigurer();
     p.setIgnoreResourceNotFound(true);

    return p;
 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>