Spring Framework Best Practices

Better architecture by design JAVAWUG BOF 27, Skills Matter, London *PP* © 2007
16th July 2007

Peter Pilgrim
Java EE Software Designer Architect Independent Contractor Financial Services Java Champion http://jroller.com/page/peter_pilgrim http://jroller.com/page/javawug

Talk Outline Spring Framework Primary School Class Spring Version 1.x Spring Version 2.0 Spring Version 2.1 and JSR 316 Spring Hints & Tips Summary

2

What is Spring? Managed Dependency Injection Framework Life-cycle of POJOS Dependency Injection for JavaBeans & Interfaces Plethora of Utility APIs and idioms 3 .

What is Spring Version 1? Simplifying J2EE Development Dynamic AOP Core Spring Data Access MVC Bean Factory Container Remoting Mail Declarative TX Scheduling 4 .

What is Spring Version 2? Simplifying J(2)EE Development AspectJ Libraries Dynamic AOP Servlet MVC Portlet MVC Tag Libs Mail Declarative TX Data Access Java 5 Bean Factory Container Annotations (TX) XML Namespaces Remoting Task Executor Scripting Languages Core Spring Scheduling 5 .

What is expected in Spring Version 2.1? Simplifying Java EE Development AspectJ Integration Dynamic AOP Core Spring Bean Factory Container OSGi Modules Familiar Data Access Alternative Data Access Annotation Driven Injection Servlet MVC Portlet MVC Tag Libs Spring Security Mail Java EE 5 Remoting Task Executor Annotation Componentisation Annotation TX Extra XML Namespaces Declarative TX Scheduling 6 .

Goals of Spring 2. local and XA transactions Task Executor AspectJ library support JPA Integration Portlet MVC 7 .0 Backwards compatible Annotation Driven Transactions Simplified Java 5 Support XML Namespace extension for ease-of-configuration Improved JMS Messaging.

1 OSGi is the biggest value add Module JARS Special OSGi XML namespace Annotation Driven Injection Spring Back-ends (JCA and LDAP support) Enhanced JPA support 8 .Goals of Spring 2.

Goals of Spring 2.1 OSGi is the biggest value add Module JARS Special OSGi XML namespace Annotation Driven Injection Spring Back-ends (JCA and LDAP support) Enhanced JPA support 9 .

but not yet!!! Spring OSGi does obscure the raw APIs Java EE 6 has a new JSR 316 Java EE may incorporate Spring's ideas Modularisation of Java EE (JSR 277 and 294) JSR 277 Java Module System JSR 294 Improved Modularity Support OSGi forces future EE architects to research new “materials” for building software 10 .Future of Spring Development Java EE JSR 316 Eventually we will be locked into Spring.

springframework..orm.w3.Configuration of Transactions: Manager & Advice <beans xmlns="http://www.springframework.springframework.org/2001/XMLSchema-instance" xmlns:aop="http://www.org/schema/beans" xmlns:xsi="http://www.hibernate3..org/schema/aop" xmlns:tx="http://www."> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <bean id="txManager" class="org. HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> 11 .org/schema/tx" xsi:schemaLocation=".springframework.

</aop:config> .springframework.springframework.service. </beans> 12 .*(.*.w3...org/2001/XMLSchema-instance" xmlns:aop="http://www.org/schema/tx" xsi:schemaLocation=".org/schema/aop" xmlns:tx="http://www..springframework..org/schema/beans" xmlns:xsi="http://www.."> <aop:config> <aop:pointcut id="projectServiceOperation" expression="execution(* websitetracker.))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="projectServiceOperation" /> </aop:config> <aop:config>...Configuration of Transactions: Pointcuts <beans xmlns="http://www.

springframework..show_sql">true</prop> <prop key="hibernate..generate_statistics">false</prop> </props></property> <property name="dataSource"><ref bean="dataSource"/></property> <property name="eventListeners"> <map> <entry key="merge"> <bean class="org.> <bean id="sessionFactory" class="org..xml</value> <value>websitetracker/domain/Website.dialect"> org.hbm.springframework.LocalSessionFactoryBean"> <property name="mappingResources"> <list> <value>websitetracker/domain/IpAddressReverse.hibernate..orm.xml</value> </list></property> <property name="hibernateProperties"> <props> <prop key="hibernate. </beans> 13 .MySQLDialect</prop> <prop key="hibernate.hibernate3. hibernate3.Configuration: Hibernate Session Factory <beans .hbm. IdTransferringMergeEventListener" /> </entry></map></property> </bean> .orm.dialect.support.

. </beans> 14 .dao.hibernate3.> <bean id="hibernateTemplate" class="org.. orm...HibernateTemplate"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> <bean id="ipAddressReverseDao" class="websitetracker.springframework.Configuration: Hibernate DAO & Services <beans .impl.IpAddressReverseDao" > <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="trackReportService" class="websitetracker.TrackReportServiceImpl" > <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> .engine.

.xml”)). } 15 ..Multiple Application Contexts Parent and Child bean factory contexts can help modularise complexity ApplicationContexts can retrieve wildcarded configuration files. return true. ) setBeanFactoryLocator( ContextSingletonBeanFactoryLocator .getInstance(“classpath:fitrader-context. setBeanFactoryLocatorKey(“FI-TRADER”). For Spring managed EJBs and MDB prefer to use ContextSingletonBeanFactoryLocator public class StartUpBean extends AbstractStatelessSessionBean { public boolean start( .

xml</value> <!-.dao layer --> <value>fitrader/dao/beans-context-dao. support.ClassPathXmlApplicationContext"> <constructor-arg index="0"> <list> <!-.AOP --> <value>fitrader/aop/beans-context-aop.xml</value> <!-..defines the entire container context --> <bean id="FI-TRADER" class="org.springframework.“fitrader-context.> <!-.Define A Master Application Context <!-.xml</value> <!-.xml” --> <beans .service layer --> <value>fitrader/service/beans-context-service.xml</value> </list> </constructor-arg> <constructor-arg index="1"><value>true</value></constructor-arg> </bean> </beans> 16 ..Transaction Manager --> <value>fitrader/dao/tx/beans-context-transaction.context.

Share Contexts Among Spring Managed EJBs Standard Spring managed EJB examples from books create and retrieve application contexts separately Consumes memory per deployment and EJB instance! Arrange for Spring managed EJBs to retrieve master application context instead Share application context Message Driven Beans especially with point-to-point queue 17 .

xml”)).Spring Managed EJB Example public class TradeRouteProcessorRemoteEJB extends AbstractStatelessSessionBean implements ITradeRouteProcessor { private static final String BEAN_NAME = "tradeRouteProcessor". } 18 .. private ITradeRouteProcessorScheduler delegate. setBeanFactoryLocator( ContextSingletonBeanFactoryLocator . } .getInstance(“classpath:fitrader-context. } protected void onEjbCreate() throws CreateException { delegate = (ITradeRouteProcessor) getBeanFactory().getBean( BEAN_NAME). setBeanFactoryLocatorKey(“FI-TRADER”). public TradeRouteProcessorRemoteEJB() { super()..

Test Driven Development Write to Java interfaces or refactor them out Consider EasyMock for functional testing AbstractSpringDatabaseTestCase is a great class to extend for an application database unit test Tactile techniques can help insert dummy data for test purposes. (JdbcTemplate) 19 .

verify() !!! 20 .Easy Mock Advice Consider a base test class for functional testing Pull up useful DAO & Service classes in the base class Refactor common ground in concrete classes Write creational methods on the base classes Call EasyMock.

0. 21 .Maven 2. Spring & Hibernate issues (prefer parallel project structure) Configure a general application context Please store under src\main\resources! Configure at least one test application context Please store under src\test\resources! Organise multiple file support for large applications Install into local repository frequently! Select all projects and hit F5!! (Grab a Biscuit and tea) Prefer Profiles to filtered resources! Eclipse tramples.0 Spring Framework Java EE Setup Eclipse IDE with Maven 2.

A Generic DAO Java 5 makes strong-typed collections easier We can write a generic DAO We can use the auto-complete feature in our IDEs We are less likely to make errors in RTTI / casting! Extendible to named queries and criterion 22 .

public abstract E findById(PK id).Generic DAO Interface public interface IPersistenceDao<E. public abstract void attachDirty(E instance). } 23 . public abstract void attachClean(E instance). PK extends Serializable> { public abstract void saveOrUpdate(E transientInstance). public abstract E merge(E detachedInstance). public abstract void delete(E persistentInstance). public abstract List<E> findByExample(E instance).

return (E) getHibernateTemplate(). PK extends Serializable> extends HibernateDaoSupport implements IPersistenceDao<E. public AbstractPersistenceDao( Class<E> type ) { super().Abstract Persistence DAO public abstract class AbstractPersistenceDao<E. PK> { private Class<E> type.saveOrUpdate(transientInstance).debug("getting "+type. } 24 . } public E findById(PK id) { logger. } . this.get( packageClassName.. } public void saveOrUpdate(E transientInstance) { getHibernateTemplate()..type = type. id).getName()+" instance with id: " + id).

class ). } @SuppressWarnings("unchecked") public List<IpAddressReverse> getAll() { return getHibernateTemplate().find( "select i from IpAddressReverse as i"). } 25 ..Concrete Generic DAO public class IpAddressReverseDao extends AbstractPersistenceDao<IpAddressReverse.Integer> { public IpAddressReverseDao() { super( IpAddressReverse. } ..

0 / 2.1 Discussion about the future of this framework Competing frameworks such as Google Guice Relevance to modularisation and architectural assembly Sharing application contexts Testing Generic DAO 26 .Executive Summary Review of Spring Framework 2.

Time for Questions? Q&A 27 .

Illustration 28 .

Sign up to vote on this title
UsefulNot useful