1.PropertyPlaceholderConfigurer了解
PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。
2.PropertyPlaceholderConfigurer加载properties文件的方式
a.通过xml方式加载properties文件
- resources下的资源文件目录
- 在spring-base.xml中配置PropertyPlaceholderConfigurer,有以下两种方式,使用其中任意一种即可
1.<context:property-placeholder location="classpath:config/app.properties"/>
2.<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
配置文件的位置
<property name="location" value="classpath:config/app.properties"></property>
多个配置文件
<property name="locations">
<list>
<value>classpath:config/app.properties</value>
</list>
</property>
</bean>
- 用配置数据源举例
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/app.properties</value>
</list>
</property>
</bean>
<bean id="dataSource_Default" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="name" value="系统数据源" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${db.minimumConnectionCount}" />
<property name="minIdle" value="${db.minimumConnectionCount}" />
<property name="maxActive" value="${db.maximumConnectionCount}" />
</bean>
- 结果
app.properties中的属性值通过${key}获取到,如${db.url}即为
app.properties中key为db.url所对应的值,
即 jdbc:jtds:sqlserver://localhost:1433;DatabaseName=test;useLOBs=false
b.通过注解方式加载properties文件
- 假如程序中有上传图片功能,我们不能将路径写死,可以将路径写到properties文件中,通过注解方式加载properties文件,来获取图片上传的路径
- 第一步与上面方式的第一步相同
- 测试
package com.wyf.core.bean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-all.xml" })
public class PropertyPlaceHolderTest {
@Value("${db.url}")
private String url;
@Test
public void test(){
System.out.println(url);
}
}
- 结果