版本:spring-framework-4.1
一、概述
为了简化读取properties文件中的配置值,Spring支持@Value注解的方式来获取,这种方式大大简化了项目的配置,业务中也提高了灵活性。
二、两种使用方法
- @Value("#{configProperties['key']}")
- @Value("${key}")
三、示例
3.1 @Value("#{configProperties['key']}")使用
3.1.1 applicationContext-value.xml
<context:component-scan base-package="com.bean.*" />
<bean id="valueTest" class="com.bean.ValueDemo" />
配置方法1:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:value.properties</value>
</list>
</property>
</bean>
配置方法2:
<util:properties id="configProperties" location="classpath:value.properties"></util:properties>
注:和配置方法1等价,这种方法需要util标签,要引入util的xsd:
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
3.1.2 value.properties
key=1
3.1.3 ValueDemo.java
@Component
public class ValueDemo {
@Value("#{configProperties['key']}")
private String value;
public String getValue() {
return value;
}
}
3.1.4 测试
@Test
public void testValue() {
BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext-value.xml");
ValueDemo valueTest=(ValueDemo)beanFactory.getBean("valueDemo");
System.out.println(valueTest.getValue());
}
结果打印:
1
3.2 @Value("${key}")使用
3.2.1 applicationContext-value.xml
方法一:在3.1.1的基础上增加:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
方法二:或者直接指定指定配置文件,完整配置如下:
<context:component-scan base-package="com.bean.*" />
<bean id="valueTest" class="com.bean.ValueDemo" />
<bean id="appProperty"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:value.properties</value>
</array>
</property>
</bean>
3.2.2 value.properties
key=1
3.2.3 ValueDemo.java
@Component
public class ValueDemo {
@Value("${key}")
private String value;
public String getValue() {
return value;
}
}
3.2.4 测试
@Test
public void testValue() {
BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext-value.xml");
ValueDemo valueTest=(ValueDemo)beanFactory.getBean("valueDemo");
System.out.println(valueTest.getValue());
}
结果打印:
1