spring framework best practices - | baby bop!
TRANSCRIPT
![Page 1: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/1.jpg)
16th July 2007
Better architecture by designJAVAWUG BOF 27, Skills Matter, London
*PP* © 2007
Peter PilgrimJava EE Software Designer ArchitectIndependent ContractorFinancial ServicesJava Championhttp://jroller.com/page/peter_pilgrim http://jroller.com/page/javawug
Spring Framework Best Practices
![Page 2: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/2.jpg)
2
Talk Outline
Spring Framework Primary School ClassSpring Version 1.xSpring Version 2.0Spring Version 2.1 and JSR 316Spring Hints & TipsSummary
![Page 3: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/3.jpg)
3
What is Spring?
Managed Dependency Injection FrameworkLife-cycle of POJOSDependency Injection for JavaBeans & InterfacesPlethora of Utility APIs and idioms
![Page 4: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/4.jpg)
4
What is Spring Version 1?
Core SpringDynamicAOP
Data Access
DeclarativeTXMail
RemotingMVC
Bean FactoryContainer
Scheduling
Simplifying J2EE Development
![Page 5: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/5.jpg)
5
What is Spring Version 2?
Core Spring
DynamicAOP
Data Access
DeclarativeTXMail
RemotingServlet MVC
Bean FactoryContainer
Scheduling
Simplifying J(2)EE Development
Annotations (TX)
AspectJLibraries
Task Executor
XML NamespacesTag Libs
Java 5
Portlet MVC
Scripting Languages
![Page 6: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/6.jpg)
6
What is expected in Spring Version 2.1?
Core Spring
DynamicAOP
Alternative DataAccess
DeclarativeTXMail
RemotingServlet MVC
Bean FactoryContainer
Scheduling
Simplifying Java EE Development
AspectJIntegration
Task ExecutorExtra XML
Namespaces Tag Libs
Java EE 5
Portlet MVC
Annotation Driven Injection
OSGi Modules
Annotation TX
Annotation Componentisation
Familiar DataAccess
Spring Security
![Page 7: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/7.jpg)
7
Goals of Spring 2.0
Backwards compatibleAnnotation Driven TransactionsSimplified Java 5 SupportXML Namespace extension for ease-of-configurationImproved JMS Messaging, local and XA transactionsTask ExecutorAspectJ library supportJPA IntegrationPortlet MVC
![Page 8: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/8.jpg)
8
Goals of Spring 2.1
OSGi is the biggest value addModule JARSSpecial OSGi XML namespaceAnnotation Driven InjectionSpring Back-ends (JCA and LDAP support)Enhanced JPA support
![Page 9: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/9.jpg)
9
Goals of Spring 2.1
OSGi is the biggest value addModule JARSSpecial OSGi XML namespaceAnnotation Driven InjectionSpring Back-ends (JCA and LDAP support)Enhanced JPA support
![Page 10: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/10.jpg)
10
Future of Spring Development Java EE JSR 316
Eventually we will be locked into Spring, but not yet!!!Spring OSGi does obscure the raw APIsJava EE 6 has a new JSR 316Java EE may incorporate Spring's ideasModularisation of Java EE (JSR 277 and 294)
JSR 277 Java Module SystemJSR 294 Improved Modularity Support
OSGi forces future EE architects to research new “materials” for building software
![Page 11: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/11.jpg)
11
Configuration of Transactions: Manager & Advice
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="...">
<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.springframework.orm.hibernate3.
HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" />
</bean> </beans>
![Page 12: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/12.jpg)
12
Configuration of Transactions: Pointcuts
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="...">
<aop:config><aop:pointcut id="projectServiceOperation"
expression="execution(* websitetracker.service.*.*(..))" /><aop:advisor advice-ref="txAdvice"
pointcut-ref="projectServiceOperation" /> </aop:config> <aop:config>...</aop:config>
...</beans>
![Page 13: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/13.jpg)
13
Configuration: Hibernate Session Factory
<beans ...> <bean id="sessionFactory" class="org.springframework.orm.
hibernate3.LocalSessionFactoryBean"> <property name="mappingResources"> <list> <value>websitetracker/domain/IpAddressReverse.hbm.xml</value> <value>websitetracker/domain/Website.hbm.xml</value> </list></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.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.springframework.orm.hibernate3.support.
IdTransferringMergeEventListener" /></entry></map></property>
</bean> ...</beans>
![Page 14: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/14.jpg)
14
Configuration: Hibernate DAO & Services
<beans ...>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory"> <ref local="sessionFactory" /> </property>
</bean>
<bean id="ipAddressReverseDao" class="websitetracker.dao.IpAddressReverseDao" > <property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="trackReportService" class="websitetracker.engine.impl.TrackReportServiceImpl" >
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean> ...</beans>
![Page 15: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/15.jpg)
15
Multiple Application Contexts
Parent and Child bean factory contexts can help modularise complexityApplicationContexts can retrieve wildcarded configuration files.For Spring managed EJBs and MDB prefer to use ContextSingletonBeanFactoryLocatorpublic class StartUpBean extends AbstractStatelessSessionBean {
public boolean start( ... )setBeanFactoryLocator( ContextSingletonBeanFactoryLocator
.getInstance(“classpath:fitrader-context.xml”)); setBeanFactoryLocatorKey(“FI-TRADER”); return true;}
![Page 16: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/16.jpg)
16
Define A Master Application Context
<!-- “fitrader-context.xml” --><beans ...>
<!-- defines the entire container context --><bean id="FI-TRADER" class="org.springframework.context.
support.ClassPathXmlApplicationContext"><constructor-arg index="0">
<list> <!-- service layer -->
<value>fitrader/service/beans-context-service.xml</value><!-- dao layer -->
<value>fitrader/dao/beans-context-dao.xml</value> <!-- Transaction Manager -->
<value>fitrader/dao/tx/beans-context-transaction.xml</value> <!-- AOP -->
<value>fitrader/aop/beans-context-aop.xml</value>
</list></constructor-arg><constructor-arg index="1"><value>true</value></constructor-arg>
</bean></beans>
![Page 17: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/17.jpg)
17
Share Contexts Among Spring Managed EJBs
Standard Spring managed EJB examples from books create and retrieve application contexts separatelyConsumes memory per deployment and EJB instance!Arrange for Spring managed EJBs to retrieve master application context insteadShare application context Message Driven Beans especially with point-to-point queue
![Page 18: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/18.jpg)
18
Spring Managed EJB Example
public class TradeRouteProcessorRemoteEJB extends AbstractStatelessSessionBeanimplements ITradeRouteProcessor{ private static final String BEAN_NAME = "tradeRouteProcessor"; private ITradeRouteProcessorScheduler delegate; public TradeRouteProcessorRemoteEJB() { super();
setBeanFactoryLocator( ContextSingletonBeanFactoryLocator
.getInstance(“classpath:fitrader-context.xml”)); setBeanFactoryLocatorKey(“FI-TRADER”); } protected void onEjbCreate() throws CreateException { delegate = (ITradeRouteProcessor)
getBeanFactory().getBean( BEAN_NAME); } ...}
![Page 19: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/19.jpg)
19
Test Driven Development
Write to Java interfaces or refactor them outConsider EasyMock for functional testingAbstractSpringDatabaseTestCase is a great class to extend for an application database unit testTactile techniques can help insert dummy data for test purposes. (JdbcTemplate)
![Page 20: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/20.jpg)
20
Easy Mock Advice
Consider a base test class for functional testingPull up useful DAO & Service classes in the base classRefactor common ground in concrete classesWrite creational methods on the base classesCall EasyMock.verify() !!!
![Page 21: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/21.jpg)
21
Maven 2.0 Spring Framework Java EE Setup
Eclipse IDE with Maven 2.0, 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 applicationsInstall into local repository frequently!
Select all projects and hit F5!! (Grab a Biscuit and tea)Prefer Profiles to filtered resources! Eclipse tramples.
![Page 22: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/22.jpg)
22
A Generic DAO
Java 5 makes strong-typed collections easierWe can write a generic DAOWe can use the auto-complete feature in our IDEsWe are less likely to make errors in RTTI / casting!Extendible to named queries and criterion
![Page 23: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/23.jpg)
23
Generic DAO Interface
public interface IPersistenceDao<E, PK extends Serializable> {
public abstract void saveOrUpdate(E transientInstance); public abstract void attachDirty(E instance); public abstract void attachClean(E instance); public abstract void delete(E persistentInstance); public abstract E merge(E detachedInstance); public abstract E findById(PK id); public abstract List<E> findByExample(E instance);}
![Page 24: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/24.jpg)
24
Abstract Persistence DAO
public abstract class AbstractPersistenceDao<E, PK extends Serializable> extends HibernateDaoSupport
implements IPersistenceDao<E, PK> {
private Class<E> type;
public AbstractPersistenceDao( Class<E> type ) { super(); this.type = type; } public void saveOrUpdate(E transientInstance) { getHibernateTemplate().saveOrUpdate(transientInstance); } public E findById(PK id) { logger.debug("getting "+type.getName()+" instance with id: " + id); return (E) getHibernateTemplate().get( packageClassName, id); }...}
![Page 25: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/25.jpg)
25
Concrete Generic DAO
public class IpAddressReverseDao extends AbstractPersistenceDao<IpAddressReverse,Integer> {
public IpAddressReverseDao() { super( IpAddressReverse.class ); } @SuppressWarnings("unchecked") public List<IpAddressReverse> getAll() { return getHibernateTemplate().find(
"select i from IpAddressReverse as i"); }
...}
![Page 26: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/26.jpg)
26
Executive Summary
Review of Spring Framework 2.0 / 2.1 Discussion about the future of this frameworkCompeting frameworks such as Google GuiceRelevance to modularisation and architectural assemblySharing application contexts TestingGeneric DAO
![Page 27: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/27.jpg)
27
Time for Questions?
Q & A
![Page 28: Spring Framework Best Practices - | Baby Bop!](https://reader035.vdocument.in/reader035/viewer/2022071600/613d17d2736caf36b7593aec/html5/thumbnails/28.jpg)
28
Illustration