Spring : Connect to multiple databases with same schema
This page last changed on Mar 03, 2006 by Kees de Kooter
The basic idea is that we put all dao's and supporting beans in an application context xml file that is loaded for each database we want to connect to. So we need a factory object to initialize the application contexts. Here is the code creating the context.
GenericApplicationContext applicationContext = new GenericApplicationContext();
// First we create datasource
DataSource dataSource = new DataSource();
dataSource.setUser(<user>);
dataSource.setPassword(<password>);
dataSource.setDatabaseName(<databse-name>);
// And whatever parameters the datasource needs
// Register the datasource in this application context
applicationContext.getBeanFactory().registerSingleton("dataSource", dataSource);
// Next load the other beans from the xml
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));