一. 前言
分散配置思路:创建properties文件,添加数据,在beans文件中先配置properties文件,再在bean中使用占位符引用数据
- 对于bean的生命周期中的很多处理接口,处理方法都是spring自带bean完成,即spring的特殊bean.
2. 当通过 context:property-placeholder 引入 属性文件的时候,有多个需要使用 , 号间隔.
3.beans文件使用占位符引用properties文件中内容:eg.${key}
二. 分散配置
通过自建properties文件,配置键值,在spring配置文件中读取,实现分散配置
db.properties文件
username=admin password=123456 driver=com.ahd.www
配置文件beans:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 引入我们的db.properties文件 --> <!-- 方式一:配置bean <bean class="PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>com/ahd/dispatcher/db.properties</value> </list> </property> </bean> --> <!-- 方式二: --> <context:property-placeholder location="classpath:com/ahd/dispatcher/db.properties"></context:property-placeholder> <bean id="dbutil" class="com.ahd.dispatcher.DBUtil"> <property name="username"><value>${username}</value></property> <property name="password"><value>${password}</value></property> <property name="drivername"><value>${driver}</value></property> </bean> </beans>
DBUtil类:
package com.ahd.dispatcher; public class DBUtil { private String username; private String password; private String drivername; public DBUtil() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDrivername() { return drivername; } public void setDrivername(String drivername) { this.drivername = drivername; } }
测试类:Test.java
package com.ahd.dispatcher; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac=new ClassPathXmlApplicationContext("com/ahd/dispatcher/beans.xml"); DBUtil dbutil = (DBUtil) ac.getBean("dbutil"); System.out.println(dbutil.getUsername()+" "+dbutil.getPassword()); } }