首先在spring的配置applicationContext.xml中配置好读取properties文件的内容。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="pphc">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>/WEB-INF/application.properties</value>
</list>
</property>
</bean>
然后定义一个类:
在类中需要注入的属性实现 setter 和 getter 方法。在 setter 方法前,添加 @Value 注解
import org.springframework.beans.factory.annotation.Value;
public class Tester {
private double price;
public double getPrice() {
return price;
}
@Value("${test.setter.value}")
public void setPrice(double price) {
this.price = price;
System.out.println("**************** price: " + price);
}
}
在properties文件中,存在这样的key=value:
test.setter.value=10
在applicationContext里面,初始化这个类:
<bean id="test" class="com.test.quartz.Tester">
</bean>
打印日志:
**************** price: 10.0