Skip to content

Instantly share code, notes, and snippets.

@aziz781
Created October 28, 2011 09:42
Show Gist options
  • Save aziz781/1321979 to your computer and use it in GitHub Desktop.
Save aziz781/1321979 to your computer and use it in GitHub Desktop.
SPRING: Datasource Configurations
<!-- Spring provides several options for making a DataSource available to your application.
(1) Getting a DataSource from JNDI -->
<bean id=”dataSource”
class=”org.springframework.jndi.JndiObjectFactoryBean“>
<property name=”jndiName”>
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
<!-- OR -->
<jee:jndi-lookup id=”dataSource” jndi-name=”/jdbc/RantzDatasource” resource-ref=”true” />
<!-- We have now wired in our server’s DataSource and its connection pooling facility
(2) Creating a DataSource connection pool -->
<bean id=“myDataSource” class=“com.mchange.v2.c3p0.ComboPooledDataSource” destroy-method=“close”>
<property name=“driverClass” value=“net.sourceforge.jtds.jdbc.Driver” />
<property name=“jdbcUrl” value=“jdbc:jtds:sqlserver://R2DDEV2:1433/sampleDB” />
<property name=“user” value=“sa” />
<property name=“password” value=“dev123″ />
</bean>
<!-- We now have a DataSource with connection pooling independent of an application server.
(3) Using a DataSource while testing
DriverManagerDataSource. This class can easily be configured and used with a unit test or suite of unit tests.-->
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
<!-- OR -->
<bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource“>
<property name=”driverClassName” value=” net.sourceforge.jtds.jdbc.Driver” />
<property name=”url” value=” jdbc:jtds:sqlserver://R2DDEV2:1433/sampleDB” />
<property name=”username” value=”sa” />
<property name=”password” value=”" />
</bean>
<!-- You now have a DataSource to use when testing your data access code.
Using JdbcTemplate
JdbcTemplate template = new JdbcTemplate(myDataSource);
All of Spring’s DAO template classes are thread-safe, we only need one JdbcTemplate instance for each DataSource in our application -->
<bean id=”jdbcTemplate” class=”org.springframework.jdbc.core.JdbcTemplate”>
<property name=”dataSource“><ref bean=”dataSource”/></property>
</bean>
<bean id=”studentDao” class=”StudentDaoJdbc”>
<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>
</bean>
<bean id=”courseDao” class=”CourseDaoJdbc”>
<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment