Wednesday, February 22, 2012

Steps to create a dataSource bean in applicationContext.xml in Spring Framework with its properties for jdbc connection string obtained from a properties file

In Spring Framework while creating a dataSource bean in applicationContext.xml, it is required to establish the jdbc connection with the connection properties like driverClassName, url, username, password being defined.

The same can be defined directly with all the property values there itself hard coded like :


But there is a better way, separate the jdbc connection dataSource bean in a seperate xml say dataSource.xml which you can import in the main applicationContext.xml

And it will be even further better if the properties  like driverClassName, url, username, password of jdbc connection string are fetched from a properties file which can be easily changed depending upon the environment without even touching the applicationContext.xml file thus the dependency is removed.

To separate the dataSource bean two files need to be created in src folder (in the same directory as applicationContext.xml):


1) dataSource.xml
2) jdbc.properties


Steps :

1) Inside src folder create a xml file dataSource.xml Paste the following in it :


Here i have used "org.springframework.jdbc.datasource.DriverManagerDataSource" as dataSource class which can be any other datasource class.


2) Inside src folder create a properties file jdbc.properties. Paste the following in it :


The Database connection string is created for mysql for database "TEST"

3) Import the created dataSource.xml in your applicationContext.xml:




That was all, you application is good to go. Got any doubts, feel free to ask/comment.