Using DataSources in DAO Classes
Let's restart with an empty ContactDao interface and a simple implementation of it. We will add more
features as we go along and explain the Spring JDBC classes as we do so. Listing 8-17 shows the empty
ContactDao interface.
Listing 8-17. ContactDao Interface and Implementation
public interface ContactDao { }
public class JdbcContactDao implements ContactDao { }
For the simple implementation, first we will add a dataSource property to it. The reason we want to
add the dataSource property to the implementation class rather than the interface should be quite
obvious: the interface does not need to know how the data is going to be retrieved and updated. By
adding get/setDataSource methods to the interface, we--in the best-case scenario--force the
implementations to declare the getter and setter stubs. Clearly, this is not a very good design practice.
Take a look at the simple JdbcContactDao class in Listing 8-18.
Listing 8-18. JdbcUserDao with dataSource Property
package com.apress.prospring3.ch8.dao.jdbc.xml;
import javax.sql.DataSource;
import com.apress.prospring3.ch8.dao.ContactDao;
public class JdbcContactDao implements ContactDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
We can now instruct Spring to configure our contactDao bean using the JdbcContactDao
implementation and set the dataSource property (see Listing 8-19; the file name is app-context-xml.xml).
Listing 8-19. Spring Application Context File with dataSource and contactDao Beans
// Namespace declaration omitted
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
<bean id="contactDao" class="com.apress.prospring3.ch8.dao.jdbc.xml.JdbcContactDao">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home