Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June...
-
Upload
ferdinand-shon-willis -
Category
Documents
-
view
219 -
download
1
Transcript of Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June...
16 de mayo de 2009
Spring FrameworkPart 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
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
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.
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
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.
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
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;
}}
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>
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 !!! ****
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>
16 de mayo de 2009
Spring’s Declarative Transactions
16 de mayo de 2009
PlatformTransactionManager Hierarchy
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()
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>
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
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.
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.
16 de mayo de 2009
Data Access Persistence Hierarchy
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>
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.
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>
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());}
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
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
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
16 de mayo de 2009 27
Thank You