public class MutiDataSourceBean extends AbstractRoutingDataSource implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(MutiDataSourceBean.class);
private static ApplicationContext ctx;
private Map<Object,Object> tds = new HashMap<Object,Object>();
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ctx = applicationContext;
}
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceType();
}
//重写InitializingBean类中方法
@Override
public void afterPropertiesSet() {
logger.info("Init MutiDataSource start...");
try {
initailizeMutiDataSource();
} catch (Exception e) {
logger.error("Init MutiDataSource error...", e);
}
logger.info("Init MutiDataSource end...");
super.afterPropertiesSet();
}
/**
* 读取配置文件中的jndi名称,获取数据源
* @throws Exception
*/
private void initailizeMutiDataSource() throws Exception {
// 读取数据源配置文件
ResourceBundle lw = ResourceBundle.getBundle("props.project-datasource-jndi");
// 初始化jndi context
Context jndiCtx = new InitialContext();
DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
// 获取配置的数据源
for(String key : lw.keySet()){
Object ds = jndiCtx.lookup(lw.getString(key));
// 将数据源交给spring管理
dlbf.registerSingleton(key, ds);
tds.put(key, ds);
}
super.setTargetDataSources(tds);
}
@Override
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
tds = targetDataSources;
super.setTargetDataSources(targetDataSources);
}
}
spring 原理
最新推荐文章于 2024-05-27 15:29:25 发布