1.PropertiesFactoryBean的使用
1.1 spring配置加入如下:
<bean id="pf" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<!--设置properties的路径-->
<property name="locations">
<list>
<value>classpath:server.properties</value>
</list>
</property>
</bean>
1.2 使用xml形式读取
<bean id="user" class="com.ws.model.User">
<!--value值格式: PropertiesFactoryBean bena的id + "." + properties的key-->
<property name="age" value="#{pf.age}"></property>
<property name="name" value="#{pf.name}"></property>
</bean>
1.3 使用注解 @Value
格式: @Value(value="xx.xx") : value值格式: PropertiesFactoryBean bena的id + "." + properties的key
@Value(value = "#{pf.name}")
private String name;
<?xml version="1.0" encoding="UTF-8"?>
<!-- 到入xml文件的约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
">
<context:component-scan
base-package="com.ws"></context:component-scan>
<!--
classpath : 只会到你的class路径中查找找文件.(推荐使用)
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找.
注意:用classpath*:需要遍历所有的classpath,所以加载速度是很慢的;因此,在规划的时候,应该尽可能规划好资源文件所在的路径,尽量避免使用classpath*.
-->
<bean id="pf" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:server.properties</value>
</list>
</property>
</bean>
<bean id="user" class="com.ws.model.User">
<property name="age" value="#{pf.age}"></property>
<property name="name" value="#{pf.name}"></property>
</bean>
</beans>
2.PropertyPlaceholderConfigurer 使用
2.1 配置
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:server.properties</value>
</list>
</property>
</bean>
2.2 xml使用
<!--通过 ${key} 读取properties文件的值 key:properties的key-->
<bean id="user" class="com.ws.model.User">
<property name="age" value="${age}"></property>
<property name="name" value="${name}"></property>
</bean>
2.3 注解使用
@Value(value = "${name}")
private String name;
3.1 spring导入标签
<!---使用此标签,无需配置PropertyPlaceholderConfigurer 或 PropertiesFactoryBean-->
<context:property-placeholder location="classpath:server.properties,config.properties"/>
<!--若文件太多,则可以参考如下:-->
<context:property-placeholder location="classpath:*.properties"/>
3.2 xml读取及注解使用参考 2 ;
4.1 使用该 注解可以免去xml中配置注解扫描器<context:property-placeholder location="classpath:*.properties"/>
4.2使用如下
@Component
@PropertySource({"classpath:server.properties","classpath:config.properties"})
//@PropertySource("classpath:server.properties") 扫描单个配置
public class User implements InitializingBean {}
//如果没有找到name对应的值,则使用默认值Hello;
@Value(value="${name:Hello}")
private String name;