为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。
一、两种使用方法
@Value的值有两类:
① ${ property : default_value }② #{ obj.property ? : default_value }
就是说,第一个注入的是外部参数对应的property,第二个则是SpEL表达式对应的内容。
那个 default_value,就是前面的值为空时的默认值。注意二者的不同。
二、配置
2.1 @Value("#{configProperties['key']}")使用 ,PropertiesFactoryBean有个属性configProperties
@Value("#{10}") 直接取值10
2.1.1配置文件
配置方法1:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:app.properties</value>
</list>
</property>
</bean>
配置方法2:
<util:properties id="configProperties" location="classpath:app.properties"></util:properties>
注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
value.propertiesw p
key=1
ValueDemo.java
- @Component
- public class ValueDemo {
- @Value("#{configProperties['key']}")
- private String value;
- public String getValue() {
- return value;
- }
- }
2.2 @Value("${key}")
2.2.1配置文件:
配置1: <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location">
<value>app.properties</value>
</property>
</bean>
配置2: <context:property-placeholder ignore-unresolvable="true" location="classpath*:/app.properties"/>
ValueDemo.java
@Component
public class ValueDemo {
@Value("${key}")
private String value;
public String getValue() {
return value;
}
}