<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jt2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSources" />
</bean>
<bean id="source" class="com.qbkj.erp.domain.JtSource">
<property name="maps">
<map merge="true" key-type="java.lang.String"
value-type="org.springframework.jdbc.core.JdbcTemplate">
<entry key="jtTest1" value-ref="jt"/>
<entry key="jtTest2" value-ref="jt2"/>
</map>
</property>
</bean>
package com.qbkj.erp.util;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.config.MapFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.qbkj.erp.domain.JtSource;
/**
* 根据传过来的字符串,返回相应的JT
* @author Administrator
* 工厂模式
*/
public class GetFactory {
public GetFactory() {
super();
// TODO Auto-generated constructor stub
}
private static GetFactory instance = new GetFactory();
public static GetFactory getInstanceFactory(){
return instance;
}
/**
* 获取JdbcTemplate
* @return
*/
public JdbcTemplate getJt(String jtName){
ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc.xml");
JtSource jtSource = (JtSource) ctx.getBean("source");
Map<Object, Object> maps = jtSource.getMaps();
Set<Entry<Object, Object>> set3 =maps.entrySet();
for(Entry<Object,Object> mapEntry : set3){
if (mapEntry.getKey().equals(jtName)) {
return (JdbcTemplate) mapEntry.getValue();
}
}
return null;
}
public static void main(String[] args) {
JdbcTemplate jdbcTemplate = GetFactory.getInstanceFactory().getJt("lala");
System.out.println(jdbcTemplate.getDataSource());
}
}
在spring中的配置文件中,可以自己配置List Map等。