This tutorial will show you how we can get a list of data sources using Spring framework. We will define multiple datasources in Spring. There may be situations where we need to define multiple datasources in Spring application.

For this tutorial we will create a standalone maven project in Eclipse.

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Sometimes we need to define a list of datasources for the purpose of insert or update in different database servers. So in this case we can have different datasource bean ids configured into the spring context XMl file and we can use those datasources as per our needs in the different classes when required by accessing the bean id reference. We can also think of a situation where we need to create a datasource holder which will give us a list of all datasources that may be used for different purpose.

I will create here a DataSourceHolder class which will actually give a list of all datasources defined in the Spring context XMl file.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Have maven installed and configured
Spring dependencies in pom.xml

Now we will see the below steps how to create a maven based spring project in Eclipse

Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-quickstart

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring-multiple-datasource

Step 2. Modify the pom.xml file as shown below.

Here in the below pom.xml file we have added two different database types, such as, MySQL and PostgreSQL because we want to work different database in this spring example to show how can we define multiple datasources in Spring.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-multiple-datasource</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-multiple-datasource</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<jdk.version>1.8</jdk.version>
		<junit.version>4.11</junit.version>
		<mysql.version>5.1.27</mysql.version>
		<postgresql.version>9.4-1200-jdbc41</postgresql.version>
		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
	</properties>

	<dependencies>
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- MySQL Driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>

		<!-- PostgreSQL -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>${postgresql.version}</version>
		</dependency>

		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 3. If you see JRE System Library[J2SE-1.4] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.4], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Create src/main/resources folder for putting the resource files.

Do right-click on the project and go New -> Source Folder. Give Folder name: as src/main/resources and click on Finish button.

Step 5. Create an XML file under src/main/resources.

Do right-click on src/main/resources in the project and go New -> file. Give File name: as spring-multiple-datasource-properties.xml and click on Finish button.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">

	<bean id="jdbcProperties"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		name="configProperties">
		<property name="order" value="99999" />
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="properties">
			<value>
				
				<!-- MySQL -->
				JDBC.MYSQL.DRIVER=com.mysql.jdbc.Driver
				JDBC.MYSQL.URL=jdbc:mysql://localhost:3306/roytuts
				JDBC.MYSQL.USERNAME=root
				JDBC.MYSQL.PASSWORD=root
				
				<!-- PostgreSQL -->
				JDBC.POSTGRESQL.DRIVER=org.postgresql.Driver
				JDBC.POSTGRESQL.URL=jdbc:postgresql://localhost:5432/roytuts
				JDBC.POSTGRESQL.USERNAME=root
				JDBC.POSTGRESQL.PASSWORD=root
				
				<!-- More Database Drivers -->
				
			</value>
		</property>
	</bean>

</beans>

Step 6. Create spring-multiple-datasource.xml file under src/main/resources with the below content.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">

	<context:annotation-config></context:annotation-config>
	<import resource="spring-multiple-datasource-properties.xml" />

	<bean id="dataSourceMySQL"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${JDBC.MYSQL.DRIVER}" />
		<property name="url" value="${JDBC.MYSQL.URL}" />
		<property name="username" value="${JDBC.MYSQL.USERNAME}" />
		<property name="password" value="${JDBC.MYSQL.PASSWORD}" />
	</bean>

	<bean id="dataSourcePOSTGRESQL"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${JDBC.POSTGRESQL.DRIVER}" />
		<property name="url" value="${JDBC.POSTGRESQL.URL}" />
		<property name="username" value="${JDBC.POSTGRESQL.USERNAME}" />
		<property name="password" value="${JDBC.POSTGRESQL.PASSWORD}" />
	</bean>

	<bean id="jdbcTemplateMySQL" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSourceMySQL" />
	</bean>

	<bean id="jdbcTemplatePOSTGRESQL" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSourcePOSTGRESQL" />
	</bean>

	<bean id="dataSourceHolder" class="com.roytuts.spring.datasource.util.DataSourceHolder"
		init-method="init" />

</beans>

Step 7. Create DataSourceHolder class with the below source code.

package com.roytuts.spring.datasource.util;

import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class DataSourceHolder {

	private Map<String, DataSource> dataSources;

	@Autowired
	private ApplicationContext applicationContext;

	public DataSourceHolder() {
	}

	@SuppressWarnings("unused")
	private void init() {
		dataSources = applicationContext.getBeansOfType(DataSource.class);
	}

	public Map<String, DataSource> getListOfDataSources() {
		return dataSources;
	}

}

Step 8. Create a main class for getting a list of datasources.

package com.roytuts.spring.datasource.util;

import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MultipleDatasourceTest {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"spring-multiple-datasource.xml");
		DataSourceHolder dataSourceHolder = (DataSourceHolder) applicationContext
				.getBean("dataSourceHolder");
		Map<String, DataSource> map = dataSourceHolder.getListOfDataSources();
		for (Map.Entry<String, DataSource> entry : map.entrySet()) {
			System.out.println("Key : " + entry.getKey());
			System.out.println("Value : " + entry.getValue());
		}
	}

}

Step 10. Run the above class you will get the below output in the console.

Apr 04, 2015 8:52:29 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@197848c: startup date [Sat Apr 04 08:52:29 IST 2015]; root of context hierarchy
Apr 04, 2015 8:52:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-multiple-datasource.xml]
Apr 04, 2015 8:52:30 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-multiple-datasource-properties.xml]
Apr 04, 2015 8:52:30 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Apr 04, 2015 8:52:30 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
Key : dataSourceMySQL
Value : org.springframework.jdbc.datasource.DriverManagerDataSource@b87145
Key : dataSourcePOSTGRESQL
Value : org.springframework.jdbc.datasource.DriverManagerDataSource@83f5ae

That’s all. Thank you for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *