参考:/spring3/spring-value-default-value/
1. @Value Examples
To set a default value in Spring expression, use Elvis operator
:
#{expression?:default value}
Few examples :
@Value("#{systemProperties[''] ?: 27017}")
private String mongodbPort;
@Value("#{config[''] ?: '127.0.0.1'}")
private String mongodbUrl;
@Value("#{ ?: 21}")
private int age;
@Value
has been available since Spring 3.0
2. @Value and Property Examples
To set a default value for property placeholder :
${property:default value}
Few examples :
//@PropertySource("classpath:/}")
//@Configuration
@Value("${:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${:172.0.0.1}'}")
private String mongodbUrl;
@Value("#{config['']?:'127.0.0.1'}")
private String mongodbUrl;
=1.2.3.4
=hello
那个 default value,就是前面的property不存在时的默认值。
写个例子测试一下:
:
=10
spring配置:
<bean
class="">
<property name="fileEncoding" value="UTF-8" />
<property name="locations">
<list>
<value>classpath:</value>
</list>
</property>
</bean>
<bean
class="">
<property name="properties" ref="configProperties" />
</bean>
测试代码:
@Value("${:300}")
private String lastTime;
@Test
public void test2() {
(lastTime);
}
输出:10
把注释
#=10
输出:300