spring之PropertyPlaceholderConfigurer学习

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);
	}
}
  • 结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值