如何在Spring @Value注释中正确指定默认值?

最初,我有以下规范:

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

这可以很好地正确获取属性文件中的值:

 isFPL = true 

但是,以下带有默认值的表达式会导致错误:

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

表达式解析失败; 嵌套exception是org.springframework.expression.spel.SpelParseException:EL1041E:(pos 28):解析有效表达式后,表达式中还有更多数据:’colon(:)’

我也尝试用$而不是#。

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

然后注释中的默认值工作正常,但我没有从属性文件中获取正确的值:

尝试使用$如下

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

还要确保将ignore-resource-no-found设置为true,以便在缺少属性文件时,将采用默认值。

另外,请将以下内容放入 –

如果使用基于xm的配置,则为上下文文件:

  

在Configuration类中如果使用Java配置:

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

对于int类型变量:

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

注意:冒号没有空格,冒号后面有一个额外的空格。

您的Spring应用程序上下文文件是否包含多个propertyPlaceholder bean,如下所示:

   

如果是这样,那么属性查找: props.isFPL只会发生在第一个属性文件( .local.properties )中,如果找不到属性,默认值( true )将生效,第二个属性文件( config.properties) )有效地忽略了这个属性。

如果您使用类似的东西,取决于您如何加载您的属性

那么@Value应该是这样的

 @Value("${isFPL:true}") 

对于String,您可以默认为null,如下所示:

 public UrlTester(@Value("${testUrl:}") String url) { this.url = url; }