Ale*_*lex 23 java spring annotations properties
最初,我有以下规范:
@Value("#{props.isFPL}")
private boolean isFPL=false;
Run Code Online (Sandbox Code Playgroud)
这可以很好地正确获取属性文件中的值:
isFPL = true
Run Code Online (Sandbox Code Playgroud)
但是,以下带有默认值的表达式会导致错误:
@Value("#{props.isFPL:false}")
private boolean isFPL=false;
Run Code Online (Sandbox Code Playgroud)
表达式解析失败; 嵌套异常是org.springframework.expression.spel.SpelParseException:EL1041E:(pos 28):解析有效表达式后,表达式中还有更多数据:'冒号(:)'
我也尝试用$而不是#.
@Value("${props.isFPL:true}")
private boolean isFPL=false;
Run Code Online (Sandbox Code Playgroud)
然后注释中的默认值工作正常,但我没有从属性文件中获取正确的值:
小智 25
尝试使用$如下
@Value("${props.isFPL:true}")
private boolean isFPL=false;
Run Code Online (Sandbox Code Playgroud)
还要确保将ignore-resource-no-found设置为true,以便在缺少属性文件时,将采用默认值.
另外,请将以下内容放入 -
如果使用基于xm的配置,则为上下文文件:
<context:property-placeholder ignore-resource-not-found="true"/>
Run Code Online (Sandbox Code Playgroud)
在Configuration类中如果使用Java配置:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
p.setIgnoreResourceNotFound(true);
return p;
}
Run Code Online (Sandbox Code Playgroud)
您的问题的确切答案取决于参数的类型。
对于“字符串”参数,您的示例代码工作正常:
@Value("#{props.string.fpl:test}")
private String fpl = "test";
Run Code Online (Sandbox Code Playgroud)
对于其他类型(例如问题中的布尔值),应该这样写:
@Value("${props.boolean.isFPL:#{false}}")
private boolean isFPL = false;
Run Code Online (Sandbox Code Playgroud)
或对于“整数”:
@Value("${props.integer.fpl:#{20}}")
Run Code Online (Sandbox Code Playgroud)
对于int类型变量:
@Value("${my.int.config: #{100}}")
int myIntConfig;
Run Code Online (Sandbox Code Playgroud)
注意:冒号前没有空格,冒号后面有一个额外的空格.
| 归档时间: |
|
| 查看次数: |
51064 次 |
| 最近记录: |