在使用spring3.0後,看到了它新增的實用@value註解,一下整理下@value註解設置默認值的方法。
首先需要在spring容器中引入properties文件,例子如下所示:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:ttt.properties</value> <value>classpath:timerbin.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean>
timerbin.properties
timer.userAge=22
一、在java代碼中使用properites中配置的值
@Value("${timer.userAge}")
private int userAge;
此時定義的userAge屬性的類需要使用註解加載到spring容器中。
二、@Value 註解設置默認值
@Value("${timer.userAge:22}")
private int userAge;
當未在properties中查找到timer.userAge時會將22賦值給userAge屬性