View RSS Feed

Spring Framework

Configuring a Spring Data Source Continued

Rate this Entry
by , 11-27-2011 at 10:02 PM (3632 Views)
There are a number of DataSource connection pool implementations provided by different vendors as well as projects like C3PO and Apache Commons DBCP providing popular open-source options. It is easy to switch between different data source implementations, because of the common DataSource interface. Spring provides a convenient data source implementations as well but it is not considered as powerful as the vendor or open source implementations. The simplest one is org.springframework.jdbc.datasource.DriverManagerD ataSource, which opens a new connection every time it is requested. In a previous tip, we showed how to configure one using xml but in this tip we will show how to configure the data source using annotations.The database properties and Java configuration are shown below, respectively.

Java Code:
JDBC DataSource Properties CarJDBC.properties
jdbc.url=jdbc:h2:tcp://localhost/~/cars 
jdbc.username=sa 
jdbc.password= 
jdbc.driver=org.h2.Driver
Java Configuration for Data Source
Java Code:
package com.acme.springexample.repository.config;
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;

@Configuration public class CarsBaseConfig {
@Value("${jdbc.url}") String jdbcUrl;
@Value("${jdbc.username}") String username;
@Value("${jdbc.password}") String password;
@Value("#{h2DataSource}") DataSource embeddedDataSource;
@Bean public DataSource dataSource() {
	return embeddedDataSource;
   }

// Remote Data Source ( just for illustrating remote connection ) 
@Bean public DataSource remoteDataSource() {
	return new DriverManagerDataSource(jdbcUrl, username, password);
    }
}

Submit "Configuring a Spring Data Source Continued" to Facebook Submit "Configuring a Spring Data Source Continued" to Digg Submit "Configuring a Spring Data Source Continued" to del.icio.us Submit "Configuring a Spring Data Source Continued" to StumbleUpon Submit "Configuring a Spring Data Source Continued" to Google

Comments