27
16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.

Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

Embed Size (px)

Citation preview

Page 1: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Spring FrameworkPart III. Portable Service Abstractions

Buenos Aires, June 2009.

Page 2: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Contents Introduction to Portable Service Abstractions

Transaction management

Data access with Spring

Data Access Objects

Data Access Persistence Hierarchy

Templating Data Access

DAO Support Classes

JDBC Example

Summary

Page 3: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Contents

Introduction to Portable Service Abstractions

Transaction management

Data access with Spring

Data Access Objects

Data Access Persistence Hierarchy

Templating Data Access

DAO Support Classes

JDBC Example

Summary

Page 4: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

OverviewAt it’s core, Spring provides:

• Dependency Injection container– Effectively organize your dependencies, takes care of plumbing.– Facilitate good programming practices, as programming to interfaces.– Build flexible applications very easy to test and configure.

• AOP support for handling crosscutting concerns– Provides J2EE services to POJOs.– E.g.: transaction management, security, logging, auditing, etc. – Portable between applications servers (no vendor lock in).

• Portable Service Abstractions– Simplified APIs for many 3rd party frameworks (Hibernate, JDBC, Quartz, JMX, ...).

These together enable you to write powerful, scalable applications using POJOs.

Page 5: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Portable Service Abstractions• Many Java EE APIs are very low-level

– Need to write lots of repetitive code– Often error-prone– Exception handling can be painful - e.g. checked exceptions

• Spring provides higher level APIs– Encapsulate low-level APIs– Eliminate boilerplate code– Simplified exception handling

⇒ Simpler application code

Page 6: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Portable Service AbstractionsSpring provides abstraction for:

• Transaction Management

• JDBC

• ORM frameworks:

– Hibernate

– JPA

– Toplink

– iBATIS

• JavaMail

• JMX

• RMI

• JMS

• Quartz

• …

Allows access to these frameworks without knowing how they actually work.

Page 7: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Contents Introduction to Portable Service Abstractions

Transaction management

Data access with Spring

Data Access Objects

Data Access Persistence Hierarchy

Templating Data Access

DAO Support Classes

JDBC Example

Summary

Page 8: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Interceptors• Interception around advive is the most fundamental advice type in Spring. AOP Alliance

compliant.

• The advice itself is represented by a bean, and must implement one of the advice interfaces (Spring 1.2 AOP support).

public class GreetingsInterceptor implements MethodInterceptor {public Object invoke(MethodInvocation invocation) throws Throwable {

System.out.println("**** HI from INTERCEPTOR !!! ****");Object rval = invocation.proceed();System.out.println("**** GOODBYE from INTERCEPTOR !!! ****");return rval;

}}

Page 9: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Interceptors• An advisor is like a small self-contained aspect that has a single piece of advice. It’s

defined with the <aop:advisor> tag.

• This is the new xml for the interceptor aspect:

<beans><bean id="counter" class="service.CounterImpl" /><bean id="greetingsInterceptor" class="aspect.GreetingsInterceptor" /><aop:config>

<aop:pointcut id="myPointcut" expression="execution(* *.go*(..))"/> <aop:advisor advice-ref="greetingsInterceptor" pointcut-ref="myPointcut"/>

</aop:config></beans>

Page 10: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Interceptors• Console output:

**** HI from INTERCEPTOR !!! ****counter = 0counter = 1counter = 2counter = 3counter = 4counter = 5counter = 6counter = 7counter = 8counter = 9counter = 10**** GOODBYE from INTERCEPTOR !!! ****

Page 11: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Transaction Manager• Spring does not directly manage transactions.

• Use transaction managers that delegate responsibility for transaction management to a platform-specific transaction implementation provided by either JTA or the persistence mechanism.

• Each transaction manager acts as a façade to a platform-specific transaction implementation.

• Makes it possible for you to work with a transaction in Spring with little regard to what the actual transaction implementation is.

• To use a transaction manager, you’ll need to declare it in your application context. For JDBC:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/>

</bean>

Page 12: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Spring’s Declarative Transactions

Page 13: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

PlatformTransactionManager Hierarchy

Page 14: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

DataSourceTransactionManager• Manages JDBC connections

– Opens and closes JDBC connections

– Stores connection in a ThreadLocal

• Manages transactions

– Connection.setAutoCommit(false)

– Connection.commit()

– Connection.rollback()

Page 15: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Tying it all togetherDeclare the Transaction Manager bean:

Declare the Transaction Advice bean.

Declare the Transaction Interceptor:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/>

</bean>

<tx:advice id="tx-advice"><tx:attributes>

<tx:method name="get*" read-only="true"/><tx:method name="*" propagation="REQUIRED"/>

</tx:attributes></tx:advice>

<aop:config><aop:pointcut id=“service” expression="execution(* service.*.*(..))"/><aop:advisor pointcut-ref=“service“ advice-ref="tx-advice"/>

</aop:config>

Page 16: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Contents Introduction to Portable Service Abstractions

Transaction management

Data access with Spring

Data Access Objects

Data Access Persistence Hierarchy

Templating Data Access

DAO Support Classes

JDBC Example

Summary

Page 17: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Data Access Objects• Service objects delegate data access to DAOs interfaces.

• This makes the service objects easily testable. You could create mock implementations for the DAOs.

• The data access layer is accessed in a persistence technology-agnostic manner.

Page 18: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Data Access Persistence HierarchyThe Problem

• JDBC force you to catch SQLExceptions. Most of them indicate a fatal condition, little can be done at runtime. Why catch them?

• SQLException is the exception thrown for all data problems: is to generic.

• Persistence frameworks like Hibernate offer many different exceptions. But they are propietary to Hibernate. You will spread them in your code.

Spring solution

• Provides several data access exceptions, each descriptive of the problem that they’re thrown.

• They are not associated with any particular persistence solution. Consistent regardless of which persistence provider you use.

• They are all unchecked exceptions. No more (empty…) catch blocks. This leaves the decision of wheter to catch an exception to the developer.

Page 19: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Data Access Persistence Hierarchy

Page 20: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Templating Data Access• Spring separates the fixed and variable parts of the data access process into

templates and callbacks.

• Spring comes with several data access templates, depending the persistence mechanism (e.g. JdbcTemplate, HibernateTemplate, etc)

<bean id="jdbcTemplate“ class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource" />

</bean>

Page 21: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

DAO Support Classes• DAO Support Classes are meant to be subclassed by your own DAO classes.

• You can call the getTemplate method to hava direct access to the underlying data access template. E.g. getJdbcTemplate(), get HibernateTemplate().

• You have also access to the class the persistence platform uses to communicate with the database. E.g. getConnection() for the JdbcDaoSupport, getSessionFactory() for HibernateDaoSupport.

Page 22: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

JDBC Example• First, declare the dataSource

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="org.hsqldb.jdbcDriver"/><property name="url" value="jdbc:hsqldb:hsql://localhost/testDB"/><property name="username" value="sa"/><property name="password" value=""/>

</bean>

Page 23: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

JDBC Example• JDBC code for addBook (26 lines) • Using JdbcDaoSupport (3 lines)

private static final String ADD_BOOK = "insert into books (id, name, author) values (?, ?, ?)";

public void addBook(Book book) {Connection conn = null;PreparedStatement stmt = null;try {

conn = dataSource.getConnection();stmt = conn.prepareStatement(ADD_BOOK);stmt.setInt(1, book.getId());stmt.setString(2, book.getName());stmt.setString(3, book.getAuthor());stmt.execute();

} catch (SQLException e) {e.printStackTrace();

} finally {try {

if (stmt != null) {stmt.close();

}if (conn != null) {

conn.close();}

} catch (SQLException e) {e.printStackTrace();

}}

}

private static final String ADD_BOOK = "insert into books (id, name, author) values (?, ?, ?)";

public void addBook(Book book) {getSimpleJdbcTemplate().update(ADD_BOOK,

book.getId(), book.getName(), book.getAuthor());}

Page 24: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Contents Introduction to Portable Service Abstractions

Transaction management

Data access with Spring

Data Access Objects

Data Access Persistence Hierarchy

Templating Data Access

DAO Support Classes

JDBC Example

Summary

Page 25: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

Summary

Spring framework:

Dependency injection

AOP

Service abstractions

Improved SOC

DRY code

Simpler code

Improved maintainability

Easier to develop and test

Let’s you focus on the core problem

Page 26: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009

References• The Spring Framework - Reference Documentation

http://static.springframework.org/spring/docs/2.5.x/reference/index.html• Introduction to the Sprinig Framework by Rod Johnson

http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework• Design Techniques and Coding Standards for J2EE Projects by Rod Johnson

http://www.theserverside.com/tt/articles/content/RodJohnsonInterview/JohnsonChapter4.pdf

• Spring in Action by Craig Walls

Page 27: Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009

16 de mayo de 2009 27

Thank You