img
To support the H2 database, we need to add the dependency on the H2 database into the project, as
shown in Table 8-3.
Table 8-3. Dependency for the H2 Database
Group ID
Artifact ID
Version
Description
1.3.160
H2 database Java library
com.h2database
h2
Spring now creates the contactDao bean by instantiating the JdbcContactDao class with the
dataSource property set to the dataSource bean.
It is good practice to make sure that all required properties on a bean have been set. The easiest way
to do this is to implement the InitializingBean interface and provide an implementation for the
afterPropertiesSet() method (see Listing 8-20). This way, you make sure that all required properties
have been set on your JdbcContactDao. For further discussion of bean initialization, refer to Chapter 5.
Listing 8-20. JdbcContactDao Implementation with InitializingBean
package com.apress.prospring3.ch8.dao.jdbc.xml;
import javax.sql.DataSource;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.InitializingBean;
import com.apress.prospring3.ch8.dao.ContactDao;
public class JdbcContactDao implements ContactDao, InitializingBean {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void afterPropertiesSet() throws Exception {
if (dataSource == null) {
throw new BeanCreationException("Must set dataSource on ContactDao");
}
}
}
The code we have looked at so far uses Spring to manage the data source and introduces the
ContactDao interface and its JDBC implementation. We also set the dataSource property on the
JdbcContactDao class in the Spring ApplicationContext file. Now we expand the code by adding the
actual DAO operations to the interface and implementation.
Exception Handling
Because Spring advocates using runtime exceptions rather than checked exceptions, you need a
mechanism to translate the checked SQLException into a runtime Spring JDBC exception. Because
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home