0% found this document useful (0 votes)
70 views28 pages

Spring JDBC Spring JDBC: For Live Spring & Hibernate Training, See THTT// LT

Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views28 pages

Spring JDBC Spring JDBC: For Live Spring & Hibernate Training, See THTT// LT

Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

2008 coreservlets.

com

Spring JDBC Part 1


Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/spring.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

2008 coreservlets.com

For live Spring & Hibernate training, see courses at http://courses.coreservlets.com/. t htt // l t /
Taught by the experts that brought you this tutorial. Available at public venues, or customized versions venues can be held on-site at your organization.
C Courses d developed and t l d d taught b M t H ll ht by Marty Hall Courses developed and taught by EE Training: http://courses.coreservlets.com/ Customized Java coreservlets.com experts (edited by Marty)
Spring, Hibernate/JPA, EJB3, Ruby/Rails Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics

Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Contact [email protected] for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

Topics in This Section p


Introduction to Spring JDBC Spring JDBC development Spring IoC integration

Java EE training: http://courses.coreservlets.com

2008 coreservlets.com

Introduction
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Motivation
public void save(Customer customer) { private boolean update(Customer customer, Connection conn) { Connection conn = null; PreparedStatement stmt = null; boolean autoCommit = false; try{ try{ stmt = conn.prepareStatement( conn prepareStatement( conn = this.dataSource.getConnection(); hi d i () "update customer set name = ? where id = ?"); autoCommit = conn.getAutoCommit(); stmt.setString(1, customer.getName()); conn.setAutoCommit(false); stmt.setString(2, customer.getId()); if(!update(customer, conn)){ return stmt.executeUpdate() > 0; insert(customer, conn); } } catch(SQLException e){ conn.commit(); throw new CustomerPersistenceException("Error: } SQL." catch(SQLException e){ + " Failed to update customer.",e); il d d ) if(conn != null){ } try{ finally{ conn.rollback(); if(stmt != null){ } try{ catch(SQLException suppressed){} stmt.close(); } stmt = null; throw new CustomerPersistenceException("Error: } SQL." catch(Exception suppressed){} + " Error saving customer: " + customer,e); } } } catch(RuntimeException e){ } if(conn != null){ try{ conn.rollback(); } catch(SQLException suppressed){} } throw new CustomerPersistenceException( Error: CustomerPersistenceException("Error: SQL." + " Error saving customer: " + customer,e); } finally{ if(conn != null){ try{ conn.setAutoCommit(autoCommit); conn.close(); conn = null; } catch(SQLException suppressed){} } } } private boolean insert(Customer customer, Connection conn) { PreparedStatement stmt = null; try{ stmt = conn.prepareStatement( conn prepareStatement( "insert into customer (id, name) values (?, ?)"); stmt.setString(1, customer.getId()); stmt.setString(2, customer.getName()); return stmt.executeUpdate() > 0; } catch(SQLException e){ throw new CustomerPersistenceException("Error: SQL." SQL " + " Failed to insert customer.",e); } finally{ if(stmt != null){ try{ stmt.close(); stmt = null; } catch(Exception suppressed){} } } }

Java EE training: http://courses.coreservlets.com

Spring JDBC Solution p g


public void save(Customer customer) { Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("customerId", customer.getId()); parameterMap.put("customerName", customer.getName()); boolean updated = simpleJdbc.update( "update customer set name = :customerName" + " where id = :customerId", parameters) > 0; :customerId if(updated){ return; } simpleJdbc.update( "insert i t customer (id name)" "i t into t (id, )" + " values (:customerId, :customerName)", parameters); }
Java EE training: http://courses.coreservlets.com

Spring JDBC p g
Standalone JDBC software
N d No dependencies on a running Spring IoC container d i i S i I C t i

Templated software
Replaces tedious Java SQL APIs Mitigates JDBC resource mismanagement risks ii C i ik

No configuration management overhead


No XML No annotations

Pure code solution


Explicit settings Verbose No class or domain modeling constraints
Interface-driven domain models Complex constructors Separates class and relational cardinality

Outperforms O/R mapping solutions Java EE training: http://courses.coreservlets.com

Spring JDBC Templates p g p


Fine-grained templates
JdbcTemplate NamedParameterJdbcTemplate

Coarse grained templates Coarse-grained


SimpleJdbcTemplate SimpleJdbcInsert p SimpleJdbcCall

SQL objects
SqlUpdate MappingSqlQuery

Java EE training: http://courses.coreservlets.com

2008 coreservlets.com

Spring I C P S i IoC Process Review


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring IoC Process p g


Develop POJO library
D fi th interfaces Define the i t f Create the implementations

Register Spring JARs


spring-core.jar i j spring-context.jar spring-beans.jar commons-logging.jar l i j

Create the bean definitions file


Default to the file name applicationContext.xml Place the file in an accessible location

Register beans
Register the spring-beans XML schema into the bean definitions file Assign bean identifiers using the id attribute Specify the bean creation method; e.g, the class attribute for direct constructor invocation

Java EE training: http://courses.coreservlets.com

Spring IoC Process Continued p g


Integrate configuration
Register the s i spring-context XML schema into the bean definitions c t t file Declare a property-placeholder element with the configuration file path assigned to the location attribute

Define bean interdependencies


Select a DI method; e.g., constructor, property setter, lookup-method, etc Specify the injection value; e.g., collaborators, values, resources, etc e g collaborators values resources etc

Initialize container
Select an ApplicationContext implementation
The integration method will depend on the target environment

Specify the location of the bean definitions file(s)

Access and use beans from the Spring IoC container


For example, via the BeanFactory API example
BeanFactory#getBean(beanName:String):Object BeanFactory#getBean(beanName:String, requiredType:Class):Object

Java EE training: http://courses.coreservlets.com

Develop POJO Library p y


package coreservlets; public class Customer { private String id; private String name; public Customer(String id, String name){ this.id this id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; t } }
Java EE training: http://courses.coreservlets.com

Develop POJO Library p y


public interface CustomerQuery { public Customer getCustomerByName(String name); }

Java EE training: http://courses.coreservlets.com

Develop POJO Library p y


public class CustomerQueryImpl implements CustomerQuery { private List<Customer> customers; public CustomerQueryImpl(List<Customer>customers) { this.customers = customers; } public Customer getCustomerByName(String name) { for(Customer c : customers){ if(c.getName().equals(name)){ return c; } } return null; } }
Java EE training: http://courses.coreservlets.com

Register Spring JARs g p g

Java EE training: http://courses.coreservlets.com

Register Spring JARs Eclipse .classpath classpath


<?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="lib" path="lib/spring-core.jar" /> <classpathentry kind="lib" path="lib/spring-beans.jar" /> <classpathentry kind="lib" path="lib/spring-context.jar" /> <classpathentry kind="lib" path="lib/commons-logging.jar"/> <classpathentry kind="con" path= org.eclipse.jdt.launching.JRE_CONTAINER /> path="org eclipse jdt launching JRE CONTAINER"/> <classpathentry kind="output" path=".eclipseclasses"/> </classpath>

Java EE training: http://courses.coreservlets.com

Create the bean definitions file


Default to applicationContext.xml Place the file in an accessible location
Classpath, filesystem or web module path

Java EE training: http://courses.coreservlets.com

Register Beans
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> </beans>

Java EE training: http://courses.coreservlets.com

Register Beans
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerQuery" class="coreservlets.mockup.CustomerQueryImpl" /> </beans>

Java EE training: http://courses.coreservlets.com

Define Bean Interdependencies


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerQuery" class="coreservlets.mockup.CustomerQueryImpl"> <constructor-arg> <list> <bean class="coreservlets.Customer"> <property name="id" value="jjoe" /> <property name="name" value="Java Joe" /> </bean> </list> </constructor-arg> / t t </bean> </beans>
Java EE training: http://courses.coreservlets.com

Initialize Container
import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/applicationContext.xml"); } }

Java EE training: http://courses.coreservlets.com

Access and Use Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/applicationContext.xml"); CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery"); Customer customer = C t t query.getCustomerByName("Java Joe"); System.out.println(customer); System out println(customer); } }
Customer id=jjoe, name=Java Joe
Java EE training: http://courses.coreservlets.com Standard output

2008 coreservlets.com

Spring S i JDBC Process


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC Process p g


Define persistence interfaces Register Spring JDBC JARs
Compilation dependencies
spring-jdbc jar spring jdbc.jar spring-tx.jar

Runtime dependencies
spring-core.jar spring core jar spring-context.jar spring-beans.jar commons-logging.jar commons-logging jar

Java EE training: http://courses.coreservlets.com

Spring JDBC Process Continued


Create persistence implementations
Defer connectivity responsibilities
Design class for DataSource dependency injection

Use Spring JDBC APIs p g


Initialize Spring JDBC template(s) with the injected DataSource

Initialize and execute the persistence objects


Instantiate the persistence objects
Inject a DataSource object for connectivity

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfaces p


public interface CustomerQuery { public Customer getCustomerByName(String name); }

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfaces p


package coreservlets; public class Customer { private String id; private String name; public Customer(String id, String name){ id this.id = id; this.name = name; } public String getId() { return id; } public String getName() { bli St i tN () return name; } }
Java EE training: http://courses.coreservlets.com

Register Spring JDBC JARs g p g

Java EE training: http://courses.coreservlets.com

Register Spring JDBC JARs Eclipse .classpath classpath


<?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="lib" path="lib/spring-core.jar" /> <classpathentry kind="lib" path="lib/spring-beans.jar" /> <classpathentry ki d lib path="lib/spring-jdbc.jar" /> l h kind="lib" h lib/ i jdb j / <classpathentry kind="lib" path="lib/spring-tx.jar" /> <classpathentry kind="lib" path="lib/commons-logging.jar"/> <classpathentry kind con kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="output" path=".eclipseclasses"/> </classpath>

Java EE training: http://courses.coreservlets.com

Implement Persistence Class p


import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.dao.*; import org.springframework.jdbc.core.simple.*; public class SpringJdbcCustomerQuery implements CustomerQuery { private SimpleJdbcTemplate jdbc; public SpringJdbcCustomerQuery(DataSource dataSource) { this.jdbc = new SimpleJdbcTemplate(dataSource); } ... }
Java EE training: http://courses.coreservlets.com

Implement Persistence Class Continued


public class SpringJdbcCustomerQuery implements CustomerQuery { ... public Customer getCustomerByName(String customerName) { try{ return this.jdbc.queryForObject( "select id, name from customer where name = ?" , customerRowMapper , customerName); } catch(EmptyResultDataAccessException e){ return null; } } ... }

Java EE training: http://courses.coreservlets.com

Initialize and Execute Persistence Objects


public class Main { public static void main(String[] args) throws Exception { DataSource dataSource = new EmbeddedDerbyDataSource( "target/ngcdb", "/setup.sql"); CustomerQuery query = new SpringJdbcCustomerQuery(dataSource); Customer customer = query.getCustomerByName( Java Joe"); query getCustomerByName("Java Joe ); System.out.println(customer); } }

Standard output

Customer id=jjoe, name=Java Joe


Java EE training: http://courses.coreservlets.com

2008 coreservlets.com

Spring S i JDBC and d Spring IoC Process


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC and Spring IoC Process


Register Spring JARs
spring-core.jar i j spring-context.jar spring-beans.jar spring-jdbc.jar spring jdbc jar spring-tx.jar commons-logging.jar

Develop persistence interfaces Create the persistence implementations


Defer connectivity responsibilities Design class for DataSource dependency injection Use Spring JDBC APIs Initialize Spring JDBC template(s) with the injected DataSource

Create the bean definitions file


Default to the file name applicationContext.xml Place the file in an accessible location Java EE training: http://courses.coreservlets.com

Spring JDBC and Spring IoC Process Continued


Register beans
R i t the spring-beans XML schema i t th bean definitions file Register th i b h into the b d fi iti fil Assign bean identifiers using the id attribute
Register a DataSource bean Register persistence implementation beans

Specify the bean creation method; e.g, the class attribute for direct constructor invocation

Integrate configuration
Register the spring-context XML schema into the bean definitions file Declare a property-placeholder element with the configuration file path assigned to the l th i d t th location attribute ti tt ib t
Map DataSource configuration into DataSource

Define bean interdependencies


S l t a DI method; e.g., constructor, property setter, lookup-method, etc Select th d t t t tt l k th d t Specify the injection value; e.g., collaborators, values, resources, etc
Register the DataSource with persistence implementations
Java EE training: http://courses.coreservlets.com

Spring JDBC and Spring IoC Process Continued


Initialize container
S l t an ApplicationContext i l Select A li ti C t t implementation t ti
The integration method will depend on the target environment

Specify the location of the bean definitions file(s)

Access and use beans from the Spring IoC container


For example, via the BeanFactory API
BeanFactory#getBean(beanName:String):Object BeanFactory#getBean(beanName:String, requiredType:Class):Object

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfaces p


public interface CustomerQuery { public Customer getCustomerByName(String name); }

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfaces p


package coreservlets; public class Customer { private String id; private String name; public Customer(String id, String name){ id this.id = id; this.name = name; } public String getId() { return id; } public String getName() { bli St i tN () return name; } }
Java EE training: http://courses.coreservlets.com

Register Spring JDBC JARs g p g

Java EE training: http://courses.coreservlets.com

Register Spring JDBC JARs Eclipse .classpath classpath


<?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="lib" path="lib/spring-core.jar" /> <classpathentry kind="lib" path="lib/spring-beans.jar" /> <classpathentry kind="lib" path="lib/spring-context.jar" /> <classpathentry kind="lib" path="lib/spring-jdbc.jar" /> <classpathentry kind="lib" path="lib/spring-tx.jar" /> <classpathentry kind= lib path="lib/commons-logging jar"/> kind="lib" path= lib/commons-logging.jar /> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="output" path=".eclipseclasses"/> </classpath>

Java EE training: http://courses.coreservlets.com

Implement Persistence Class p


import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.dao.*; import org.springframework.jdbc.core.simple.*; public class SpringJdbcCustomerQuery implements CustomerQuery { private SimpleJdbcTemplate jdbc; public SpringJdbcCustomerQuery(DataSource dataSource) { jdbc = new SimpleJdbcTemplate(dataSource); } ... }
Java EE training: http://courses.coreservlets.com

Implement Persistence Class Continued


public class SpringJdbcCustomerQuery implements CustomerQuery { ... private ParameterizedRowMapper<Customer> customerRowMapper = new ParameterizedRowMapper<Customer>(){ public Customer mapRow(ResultSet rslt, int rowNum) throws SQLException { return new Customer(rslt.getString("id"), rslt.getString( name )); rslt getString("name")); } }; ... }

Java EE training: http://courses.coreservlets.com

Implement Persistence Class Continued


public class SpringJdbcCustomerQuery implements CustomerQuery { ... public Customer getCustomerByName(String customerName) { try{ return jdbc.queryForObject( "select id, name from customer where name = ?" , customerRowMapper , customerName); } catch(EmptyResultDataAccessException e){ return null; } } ... }

Java EE training: http://courses.coreservlets.com

Create the bean definitions file


Default to applicationContext.xml Place the file in an accessible location
Classpath, filesystem or web module path

Java EE training: http://courses.coreservlets.com

Register Beans
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> </beans>

Java EE training: http://courses.coreservlets.com

Register Beans
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerQuery" class="coreservlets.SpringJdbcCustomerQuery" /> <bean id="dataSource" class="coreservlets.util.EmbeddedDerbyDataSource" /> </beans>

Java EE training: http://courses.coreservlets.com

Integrate Configuration g g
Create the properties file
dataSource.properties

Place the file in an accessible location


classpath root l th t

Java EE training: http://courses.coreservlets.com

Integrate Configuration g g
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="customerQuery" class="coreservlets.SpringJdbcCustomerQuery" /> <bean id="dataSource" class="coreservlets.util.EmbeddedDerbyDataSource" /> </beans> /b

Java EE training: http://courses.coreservlets.com

Integrate Configuration g g
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:property-placeholder location="classpath:/dataSource.properties" /> <bean id="customerQuery" class="coreservlets.SpringJdbcCustomerQuery" /> <bean id="dataSource" b id "d t S " class="coreservlets.util.EmbeddedDerbyDataSource" /> </beans>
Java EE training: http://courses.coreservlets.com

Define Bean Interdependencies


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns http://www.springframework.org/schema/beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerQuery" class="coreservlets.SpringJdbcCustomerQuery"> <constructor-arg ref="dataSource" /> </bean> <bean id="dataSource" class="coreservlets.util.EmbeddedDerbyDataSource"> <constructor-arg value="${derby.db.name}" /> <constructor-arg> <list> <value>${derby.db.setup}</value> </list> /li t </constructor-arg> </bean> Java EE training: http://courses.coreservlets.com </beans>

Initialize Container
import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/applicationContext.xml"); } }

Java EE training: http://courses.coreservlets.com

Access and Use Beans


import org.springframework.context.support.*; public class Main { public static void main(String[]args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext( "/applicationContext.xml"); CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery"); Customer customer = C t t query.getCustomerByName("Java Joe"); System.out.println(customer); System out println(customer); } }
Customer id=jjoe, name=Java Joe
Java EE training: http://courses.coreservlets.com Standard output

2008 coreservlets.com

Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC and Spring IoC Process


Spring JARs spring-jdbc.jar, spring-tx.jar, spring-core.jar, springi jdb j i t j i j i context.jar, spring-beans.jar, commons-logging.jar Develop persistence implementations
Initialize JDBC template(s) with a DataSource Defer connectivity responsibilities. Use constructor or property setter DI integrating with the DataSource

C Create applicationContext.xml
Save in an accessible location

Register and wire beans g


Register spring-beans XML schema Create persistence and DataSource beans Wire DataSource bean into persistence beans using constructor or property setter DI
Java EE training: http://courses.coreservlets.com

Spring JDBC and Spring IoC Process Continued


Integrate configuration
C t and save the properties file in an accessible location Create d th ti fil i ibl l ti Register spring-context XML schema Create a property-placeholder declaration with a location attribute

Initialize container
Instantiate a BeanFactory
e g ClassPathXmlApplicationContext e.g.,

Access and use beans from the Spring IoC container


Pass the bean name to BeanFactory#getBean(beanName:String):Object

Java EE training: http://courses.coreservlets.com

2008 coreservlets.com

Questions? Q ti ?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like