使用spring的特殊bean,完成分散配置:
DBUtil.java
package com.hsp.dispatch;
public class DBUtil {
private String drivername;
private String url;
private String name;
private String pwd;
// **************************************
public String getDrivername() {
return drivername;
}
public void setDrivername(String drivername) {
this.drivername = drivername;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
db.properties
name=scott
drivername=oracle:jdbc:driver:OracleDirver
url=jdbc:oracle:thin:@127.0.0.1:1521:hsp
pwd=tiger
# key=value
db2.properties
db2.name=scott3
db2.drivername=oracle:jdbc:driver:OracleDirver3
db2.url=jdbc:oracle:thin:@127.0.0.1:1521:hsp3
db2.pwd=tiger3
# key=value
beans.xml
<?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文件 -->
<context:property-placeholder
location="classpath:com/hsp/dispatch/db.properties,classpath:com/hsp/dispatch/db2.properties" />
<!-- 配置一DBUtil对象 $占位符号 -->
<bean id="dbutil" class="com.hsp.dispatch.DBUtil">
<property name="name" value="${name}" />
<property name="drivername" value="${drivername}" />
<property name="url" value="${url}" />
<property name="pwd" value="${pwd}" />
</bean>
<!-- 配置一DBUtil对象 -->
<bean id="dbutil2" class="com.hsp.dispatch.DBUtil">
<property name="name" value="${db2.name}" />
<property name="drivername" value="${db2.drivername}" />
<property name="url" value="${db2.url}" />
<property name="pwd" value="${db2.pwd}" />
</bean>
</beans>
App1.java
package com.hsp.dispatch;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/dispatch/beans.xml");
DBUtil dbUtil=(DBUtil) ac.getBean("dbutil2");
System.out.println(dbUtil.getDrivername()+" "+dbUtil.getName());
}
}