packagecom.wanda.crs.common.core;importjava.io.IOException;importjava.util.HashMap;importjava.util.Iterator;importjava.util.LinkedHashMap;importjava.util.List;importjava.util.Map;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.support.BeanDefinitionBuilder;importorg.springframework.beans.factory.support.DefaultListableBeanFactory;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;importorg.springframework.context.ApplicationEvent;importorg.springframework.context.ApplicationListener;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.event.ContextRefreshedEvent;importorg.springframework.jdbc.core.JdbcTemplate;importcom.wanda.crs.common.entity.DbConfig;importcom.wanda.crs.utils.PropertyUtil;public class DynamicCreateDataSourceBean implementsApplicationContextAware,
ApplicationListener{private static final String DBFILE_PATH = "/jdbc.properties";privateConfigurableApplicationContext app;privateJdbcTemplate jdbcTemplate;privateDynamicDataSource dataSource;public voidsetJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate =jdbcTemplate;
}public voidsetDataSource(DynamicDataSource dataSource) {this.dataSource =dataSource;
}
@Overridepublic voidsetApplicationContext(ApplicationContext app)throwsBeansException {this.app =(ConfigurableApplicationContext)app;
}
@Overridepublic voidonApplicationEvent(ApplicationEvent event) {//如果是容器刷新事件OR Start Event
if (event instanceofContextRefreshedEvent) {try{
regDynamicBean();
}catch(IOException e) {
e.printStackTrace();
}//System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
}
}private void regDynamicBean() throwsIOException {//解析属性文件,得到数据源Map
Map mapCustom =parsePropertiesFile();//把数据源bean注册到容器中
addSourceBeanToApp(mapCustom);
}/*** 功能说明:根据DataSource创建bean并注册到容器中
*
*@paramacf
*@parammapCustom*/
private void addSourceBeanToApp(MapmapCustom) {
DefaultListableBeanFactory acf=(DefaultListableBeanFactory) app.getAutowireCapableBeanFactory();
PropertyUtil propertyUtil= newPropertyUtil();
String readOnly= propertyUtil.getProperty(DBFILE_PATH, "readOnly");
String connectionTimeout= propertyUtil.getProperty(DBFILE_PATH, "connectionTimeout");
String idleTimeout= propertyUtil.getProperty(DBFILE_PATH, "idleTimeout");
String maxLifetime= propertyUtil.getProperty(DBFILE_PATH, "maxLifetime");
String maximumPoolSize= propertyUtil.getProperty(DBFILE_PATH, "maximumPoolSize");
String connectionTestQuery= propertyUtil.getProperty(DBFILE_PATH, "connectionTestQuery");
String DATASOURCE_BEAN_CLASS= "com.zaxxer.hikari.HikariDataSource";
BeanDefinitionBuilder bdb;
Iterator iter =mapCustom.keySet().iterator();
Map targetDataSources = new LinkedHashMap();//BeanDefinition beanDefinition = new ChildBeanDefinition("portal");//将默认数据源放入 targetDataSources map中
targetDataSources.put("portal1", app.getBean("portal"));//根据数据源得到数据,动态创建数据源bean 并将bean注册到applicationContext中去
while(iter.hasNext()) {//bean ID
String beanKey =iter.next();//创建bean
bdb =BeanDefinitionBuilder.rootBeanDefinition(DATASOURCE_BEAN_CLASS);
bdb.getBeanDefinition().setAttribute("id", beanKey);
bdb.getBeanDefinition().setAttribute("destroy-method", "close");
bdb.addPropertyValue("driverClassName", mapCustom.get(beanKey).getDriverclass());
bdb.addPropertyValue("jdbcUrl", mapCustom.get(beanKey).getJdbcurl());
bdb.addPropertyValue("username", mapCustom.get(beanKey).getUsername());
bdb.addPropertyValue("password", mapCustom.get(beanKey).getPassword());
bdb.addPropertyValue("readOnly", readOnly);
bdb.addPropertyValue("connectionTimeout", Integer.parseInt(connectionTimeout));
bdb.addPropertyValue("idleTimeout", Integer.parseInt(idleTimeout));
bdb.addPropertyValue("maxLifetime", Integer.parseInt(maxLifetime));
bdb.addPropertyValue("maximumPoolSize", Integer.parseInt(maximumPoolSize));
bdb.addPropertyValue("connectionTestQuery", connectionTestQuery);//注册bean
acf.registerBeanDefinition("ds" +beanKey, bdb.getBeanDefinition());//放入map中,注意一定是刚才创建bean对象
targetDataSources.put(beanKey, app.getBean("ds" +beanKey));
}//将创建的map对象set到 targetDataSources;
dataSource.setTargetDataSources(targetDataSources);//必须执行此操作,才会重新初始化AbstractRoutingDataSource 中的//resolvedDataSources,也只有这样,动态切换才会起效
dataSource.afterPropertiesSet();
}/*** 功能说明:GET ALL SM_STATIONS FROM DB1
*
*@return*@throwsIOException*/@SuppressWarnings("rawtypes")private MapparsePropertiesFile()throwsIOException {
String sql= "SELECT ID_COMPANY,DRIVERCLASS,JDBCURL,USERNAME,PASSWORD FROM CRS_DB_CONFIG WHERE IS_DEL=0 AND IS_ENABLED=10091020";
List list=jdbcTemplate.queryForList(sql);
Iterator iterator=list.iterator();
Map mds = new HashMap();while(iterator.hasNext()) {
Map map4station=(Map) iterator.next();
DbConfig dsi= newDbConfig();
dsi.setIdCompany((String)map4station.get("ID_COMPANY"));
dsi.setDriverclass((String)map4station.get("DRIVERCLASS"));
dsi.setJdbcurl((String)map4station.get("JDBCURL"));
dsi.setUsername((String)map4station.get("USERNAME"));
dsi.setPassword((String)map4station.get("PASSWORD"));
mds.put(dsi.getIdCompany(), dsi);
}returnmds;
}
}