Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

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

Initially, I have the following spec:

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

This works fine correctly getting the value from the property file:

isFPL = true

However, the following expression with default results in the error:

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

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E:(pos 28): After parsing a valid expression, there is still 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 annotation works fine but I did not get the correct value from the Properties file:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...