Thursday, March 1, 2012

Spring java database configuration


import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
// spring config that loads the properties file
@ImportResource(value = { "classpath:db.xml" })
public class DBConfig {
@Resource
private DataSource oracleDataSource;

@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(oracleDataSource);
}
}


db.xml contains database configuration and looks like

<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="oracleDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@<host>:1521/<database>" />
<property name="username" value="" />
<property name="password" value="" />
<property name="initialSize" value="10" />
<property name="maxActive" value="10" />
</bean>
<bean id="sqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
<property name="url" value="jdbc:microsoft:sqlserver://<host>:1433;DatabaseName=<database>" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>

No comments:

Post a Comment