Spring Framework Dhaval   Shah
Contents Why? Overview DI/IoC Spring-Hibernate integration Transaction Manager AOP
Why Use Spring? Wiring of components (Dependency Injection) Promotes/simplifies decoupling, design to interfaces, TDD Declarative programming without J2EE Easily configured aspects, esp. transaction support Simplify use of popular technologies Abstractions insulate application from specifics, eliminate redundant code, and handle common error conditions Underlying technology specifics still accessible (closures)
Why Use Spring? Well designed Easy to extend Many reusable classes
Spring Overview Lightweight Inversion of Control Aspect Oriented Container Framework
Spring Framework
Spring DI/IoC Dependency Inversion Principle High level modules should not depend upon low level modules, both should depend upon abstractions Abstractions should not depend upon details, details should depend upon abstractions Three defining factors of bad code Rigidity Fragility Immobility
Spring DI/IoC (Cont’d) Ways to instantiate container/working with application context ClassPathXmlApplicationContext FileSystemXmlApplicationContext XmlWebApplicationContext Syntax ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {  "cfg/applicationContext.xml"}); Variations on dependency injection Constructor-based (PicoContainer, Spring) Setter-based (Spring) Interface based (Avalon)
Spring DI/IoC (Cont’d) Property and constructor based IoC <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <property name=&quot;beanOne&quot;><ref bean=&quot;anotherExampleBean&quot;/></property> <property name=&quot;beanTwo&quot;><ref bean=&quot;yetAnotherBean&quot;/></property> <property name=&quot;integerProperty&quot;>1</property> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <constructor-arg><ref bean=&quot;anotherExampleBean&quot;/></constructor-arg> <constructor-arg><ref bean=&quot;yetAnotherBean&quot;/></constructor-arg> <constructor-arg><value>1</value></constructor-arg> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/>
Spring DI/IoC (Cont’d) Bean’s Lifecycle
Dependency Injection (cont'd) Singleton Vs Prototype <bean id=&quot;myBean&quot; class=&quot;src.beans.TestBean&quot; singleton=&quot;false&quot;> <property name=&quot;name&quot; value=&quot;JAVA&quot;/> </bean> Intitialization & Destruction <bean id=&quot;myBean&quot; class=&quot;src.beans.TestBean&quot; init-method=&quot;setUp&quot; destroy-method=&quot;tearDown&quot;> <property name=&quot;name&quot; value=&quot;JAVA&quot;/> </bean> Referencing other beans <bean id=&quot;businesslogicbean&quot; class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;> <property name=&quot;target&quot;> <ref local=&quot;beanTarget&quot;/> </property> </bean> <bean id=&quot;beanTarget&quot; class=&quot;src.aop.BusinessLogic&quot;/>
Dependency Injection (cont'd) BeanFactory configured components need have no Spring dependencies Simple JavaBeans Beans are singletons by default Properties may be simple values or references to other beans Built-in support for defining Lists, Maps, Sets, and Properties collection types.  Custom PropertyEditors may be defined to convert string values to other, arbitrary types.
Spring AOP
AOP Fundamentals Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns Transaction management Security Logging Auditing Locking
AOP Fundamentals Aspect - Implementation of a cross-cutting functionality (E.g logging)  Joinpoint - Execution point of application where an aspect can be plugged (e.g methods) Advice – Actual implementation of aspect Pointcut - A set of joinpoints specifying where advice should be applied  Introduction – Allows to add methods or fields to existing classes. Target – Class that is being advised Proxy – Object created after applying advice to target
AOP Fundamentals Weaving - Process of applying aspects to a target object to create a new, proxied object Can take place at – Compile time Class load time Runtime
Spring AOP Advice Types- Advice Type Interface Description Around org.aopalliance.intercept.MethodInterceptor Intercepts call to the target method Before org.springframework.aop.BeforeAdvice Called before the target method is invoked After org.springframework.aop.AfterReturningAdvice Called after the target method is invoked Throws org.springframework.aop.ThrowsAdvice Called when target method throws an exception
Spring AOP Example
Transactions
Spring Transaction Manager Transaction Manager Implementation Purpose org.springframework.jdbc.datasource.DataSourceTransactionManager Manages transactions on a single JDBC DataSource. org.springframework.orm.hibernate.HibernateTransactionManager Used to manage transactions when Hibernate is the persistence mechanism. org.springframework.orm.jdo.JdoTransactionManager Used to manage transactions when JDO is used for persistence. org.springframework.transaction.jta.JtaTransactionManager Manages transactions using a Java Transaction API (JTA ) implementation. Must be used when a transaction spans multiple resources. org.springframework.orm.ojb.PersistenceBrokerTransactionManager Manages transactions when Apache’s Object Relational Bridge (OJB) is used for persistence.
Transaction Configuration <bean id=&quot;sessionFactory&quot;  class=&quot;org.springframework.orm.hibernate.LocalSessionFactoryBean&quot;> <property name=&quot;dataSource&quot;><ref bean=&quot;dataSource&quot;/></property> <property name=&quot;mappingResources&quot;> <list> <value>com/../model/*.hbm.xml</value> </list> </property> </bean> <bean id=&quot;transactionManager” class=&quot;org.springframework.orm.hibernate.HibernateTransactionManager&quot;> <property name=&quot;sessionFactory&quot;> <ref bean=&quot;sessionFactory&quot;/> </property> </bean>
Declarative Transactions Declarative transactional support can be added to any bean by using TransactionProxyFactoryBean Similar to EJB, transaction attributes may be defined on a per-method basis Also allows definition of pre- and post- interceptors (e.g. for security)
Injecting Transaction Support <bean id=“reservationService&quot;  class=&quot;org.springframework.transaction.interceptor.TransactionProxyFactoryBean&quot;>  <property name=&quot;transactionManager&quot;> <ref bean=&quot;transactionManager&quot;/> </property>  <property name=&quot;target&quot;><ref local=“reservationServiceTarget&quot;/></property> <property name=&quot;transactionAttributes&quot;>  <props> <prop key=“reserveRoom*&quot;>PROPAGATION_REQUIRED</prop>  <prop key=&quot;*&quot;>PROPAGATION_REQUIRED,readOnly</prop>  </props>  </property>  </bean> Declarative transaction support for single bean
Transaction Autoproxy < bean id=&quot;autoproxy&quot;  class=&quot;org...DefaultAdvisorAutoProxyCreator&quot;> </bean> <bean id=&quot;transactionAdvisor&quot; class=&quot;org...TransactionAttributeSourceAdvisor&quot; autowire =&quot;constructor&quot; > </bean> <bean id=&quot;transactionInterceptor&quot; class=&quot;org...TransactionInterceptor&quot; autowire =&quot;byType&quot;>  </bean> <bean id=&quot;transactionAttributeSource&quot; class=&quot;org...AttributesTransactionAttributeSource&quot; autowire =&quot;constructor&quot;> </bean> <bean id=&quot;attributes&quot; class=&quot;org...CommonsAttributes&quot; /> Caches metadata from classes Generic autoproxy support Applies transaction using transactionManager Invokes interceptor based on attributes
Data Access
Data Access DAO support provides pluggable framework for persistence Currently supports JDBC, Hibernate, JDO, and iBatis Defines consistent exception hierarchy (based on RuntimeException) Provides abstract “Support” classes for each technology Template methods define specific queries
Hibernate DAO Example public class ReservationDaoImpl extends HibernateDaoSupport  implements ReservationDao { public Reservation getReservation (Long orderId) { return (Reservation)getHibernateTemplate().load(Reservation .class,  orderId); } public void saveReservation (Reservation r) { getHibernateTemplate().saveOrUpdate(r); } public void remove(Reservation Reservation) { getHibernateTemplate().delete(r); }
Hibernate DAO (cont’d) public Reservation[] findReservations(Room room) { List list = getHibernateTemplate().find( &quot;from Reservation reservation “ + “  where reservation.resource =? “ + “  order by reservation.start&quot;, instrument); return (Reservation[]) list.toArray(new Reservation[list.size()]);
Hibernate DAO (cont’d) public Reservation[] findReservations(final DateRange range) { final HibernateTemplate template = getHibernateTemplate(); List list = (List) template.execute(new HibernateCallback() { public Object doInHibernate(Session session) { Query query = session.createQuery( &quot;from Reservation r “ + “  where r.start > :rangeStart and r.start < :rangeEnd “); query.setDate(&quot;rangeStart&quot;, range.getStartDate() query.setDate(&quot;rangeEnd&quot;, range.getEndDate()) return query.list(); } }); return (Reservation[]) list.toArray(new Reservation[list.size()]); } }
Hibernate Example <bean id=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate.LocalSessionFactoryBean&quot;> <property name=&quot;dataSource&quot;><ref bean=&quot;dataSource&quot;/></property> <property name=&quot;mappingResources&quot;> <list> <value>com/jensenp/Reservation/Room.hbm.xml</value> <value>com/jensenp/Reservation/Reservation.hbm.xml</value> <value>com/jensenp/Reservation/Resource.hbm.xml</value>  </list> </property>  <property name=&quot;hibernateProperties&quot;> <props> <prop key=&quot;hibernate.dialect&quot;>${hibernate.dialect}</prop> <prop key=&quot;hibernate.hbm2ddl.auto&quot;>${hibernate.hbm2ddl.auto} </prop> <prop key=&quot;hibernate.show_sql&quot;>${hibernate.show_sql}</prop> </props> </property> </bean> <bean id=“reservationDao&quot; class=&quot;com.jensenp.Reservation.ReservationDaoImpl&quot;> <property name=&quot;sessionFactory&quot;><ref bean=&quot;sessionFactory&quot;/> </property> </bean>
JDBC Support JDBCTemplate provides Translation of SQLExceptions to more meaningful Spring Runtime exceptions Integrates thread-specific transactions MappingSQLQuery simplifies mapping of ResultSets to Java objects
Web Framework
DispatcherServlet The DispatcherServlet is the Spring Front Controller Initializes WebApplicationContext Uses  /WEB-INF/[servlet-name]-servlet.xml  by default WebApplicationContext is bound into ServletContext
DispatcherServlet Configuration HandlerMapping Routing of requests to handlers HandlerAdapter Adapts to handler interface.  Default utilizes  Controller s HandlerExceptionResolver Maps exceptions to error pages Similar to standard Servlet, but more flexible ViewResolver Maps symbolic name to view
Dispatcher Servlet Configuration MultipartResolver Handling of file upload LocaleResolver Default uses HTTP accept header, cookie, or session
Controllers Controller interface defines one method ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception ModelAndView consists of a view identifier and a Map of model data
Controller Implementations CommandControllers bind parameters to data objects AbstractCommandController AbstractFormController SimpleFormController WizardFormController
References Spring’s homepage: http://www.springframework.org “ Introducing the Spring Framework” by Rod Johnson: http://theserverside.com/news/thread.jsp?thread_id=21893 “ Inversion of control containers and dependency injection” by Martin Fowler: http://www.martinfowler.com/articles/injection.html AOP Alliance: http://aopalliance.sourceforge.net

Spring overview

  • 1.
  • 2.
    Contents Why? OverviewDI/IoC Spring-Hibernate integration Transaction Manager AOP
  • 3.
    Why Use Spring?Wiring of components (Dependency Injection) Promotes/simplifies decoupling, design to interfaces, TDD Declarative programming without J2EE Easily configured aspects, esp. transaction support Simplify use of popular technologies Abstractions insulate application from specifics, eliminate redundant code, and handle common error conditions Underlying technology specifics still accessible (closures)
  • 4.
    Why Use Spring?Well designed Easy to extend Many reusable classes
  • 5.
    Spring Overview LightweightInversion of Control Aspect Oriented Container Framework
  • 6.
  • 7.
    Spring DI/IoC DependencyInversion Principle High level modules should not depend upon low level modules, both should depend upon abstractions Abstractions should not depend upon details, details should depend upon abstractions Three defining factors of bad code Rigidity Fragility Immobility
  • 8.
    Spring DI/IoC (Cont’d)Ways to instantiate container/working with application context ClassPathXmlApplicationContext FileSystemXmlApplicationContext XmlWebApplicationContext Syntax ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { &quot;cfg/applicationContext.xml&quot;}); Variations on dependency injection Constructor-based (PicoContainer, Spring) Setter-based (Spring) Interface based (Avalon)
  • 9.
    Spring DI/IoC (Cont’d)Property and constructor based IoC <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <property name=&quot;beanOne&quot;><ref bean=&quot;anotherExampleBean&quot;/></property> <property name=&quot;beanTwo&quot;><ref bean=&quot;yetAnotherBean&quot;/></property> <property name=&quot;integerProperty&quot;>1</property> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <constructor-arg><ref bean=&quot;anotherExampleBean&quot;/></constructor-arg> <constructor-arg><ref bean=&quot;yetAnotherBean&quot;/></constructor-arg> <constructor-arg><value>1</value></constructor-arg> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/>
  • 10.
    Spring DI/IoC (Cont’d)Bean’s Lifecycle
  • 11.
    Dependency Injection (cont'd)Singleton Vs Prototype <bean id=&quot;myBean&quot; class=&quot;src.beans.TestBean&quot; singleton=&quot;false&quot;> <property name=&quot;name&quot; value=&quot;JAVA&quot;/> </bean> Intitialization & Destruction <bean id=&quot;myBean&quot; class=&quot;src.beans.TestBean&quot; init-method=&quot;setUp&quot; destroy-method=&quot;tearDown&quot;> <property name=&quot;name&quot; value=&quot;JAVA&quot;/> </bean> Referencing other beans <bean id=&quot;businesslogicbean&quot; class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;> <property name=&quot;target&quot;> <ref local=&quot;beanTarget&quot;/> </property> </bean> <bean id=&quot;beanTarget&quot; class=&quot;src.aop.BusinessLogic&quot;/>
  • 12.
    Dependency Injection (cont'd)BeanFactory configured components need have no Spring dependencies Simple JavaBeans Beans are singletons by default Properties may be simple values or references to other beans Built-in support for defining Lists, Maps, Sets, and Properties collection types. Custom PropertyEditors may be defined to convert string values to other, arbitrary types.
  • 13.
  • 14.
    AOP Fundamentals Aspect-orientedprogramming (AOP) provides for simplified application of cross-cutting concerns Transaction management Security Logging Auditing Locking
  • 15.
    AOP Fundamentals Aspect- Implementation of a cross-cutting functionality (E.g logging) Joinpoint - Execution point of application where an aspect can be plugged (e.g methods) Advice – Actual implementation of aspect Pointcut - A set of joinpoints specifying where advice should be applied Introduction – Allows to add methods or fields to existing classes. Target – Class that is being advised Proxy – Object created after applying advice to target
  • 16.
    AOP Fundamentals Weaving- Process of applying aspects to a target object to create a new, proxied object Can take place at – Compile time Class load time Runtime
  • 17.
    Spring AOP AdviceTypes- Advice Type Interface Description Around org.aopalliance.intercept.MethodInterceptor Intercepts call to the target method Before org.springframework.aop.BeforeAdvice Called before the target method is invoked After org.springframework.aop.AfterReturningAdvice Called after the target method is invoked Throws org.springframework.aop.ThrowsAdvice Called when target method throws an exception
  • 18.
  • 19.
  • 20.
    Spring Transaction ManagerTransaction Manager Implementation Purpose org.springframework.jdbc.datasource.DataSourceTransactionManager Manages transactions on a single JDBC DataSource. org.springframework.orm.hibernate.HibernateTransactionManager Used to manage transactions when Hibernate is the persistence mechanism. org.springframework.orm.jdo.JdoTransactionManager Used to manage transactions when JDO is used for persistence. org.springframework.transaction.jta.JtaTransactionManager Manages transactions using a Java Transaction API (JTA ) implementation. Must be used when a transaction spans multiple resources. org.springframework.orm.ojb.PersistenceBrokerTransactionManager Manages transactions when Apache’s Object Relational Bridge (OJB) is used for persistence.
  • 21.
    Transaction Configuration <beanid=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate.LocalSessionFactoryBean&quot;> <property name=&quot;dataSource&quot;><ref bean=&quot;dataSource&quot;/></property> <property name=&quot;mappingResources&quot;> <list> <value>com/../model/*.hbm.xml</value> </list> </property> </bean> <bean id=&quot;transactionManager” class=&quot;org.springframework.orm.hibernate.HibernateTransactionManager&quot;> <property name=&quot;sessionFactory&quot;> <ref bean=&quot;sessionFactory&quot;/> </property> </bean>
  • 22.
    Declarative Transactions Declarativetransactional support can be added to any bean by using TransactionProxyFactoryBean Similar to EJB, transaction attributes may be defined on a per-method basis Also allows definition of pre- and post- interceptors (e.g. for security)
  • 23.
    Injecting Transaction Support<bean id=“reservationService&quot; class=&quot;org.springframework.transaction.interceptor.TransactionProxyFactoryBean&quot;> <property name=&quot;transactionManager&quot;> <ref bean=&quot;transactionManager&quot;/> </property> <property name=&quot;target&quot;><ref local=“reservationServiceTarget&quot;/></property> <property name=&quot;transactionAttributes&quot;> <props> <prop key=“reserveRoom*&quot;>PROPAGATION_REQUIRED</prop> <prop key=&quot;*&quot;>PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> Declarative transaction support for single bean
  • 24.
    Transaction Autoproxy <bean id=&quot;autoproxy&quot; class=&quot;org...DefaultAdvisorAutoProxyCreator&quot;> </bean> <bean id=&quot;transactionAdvisor&quot; class=&quot;org...TransactionAttributeSourceAdvisor&quot; autowire =&quot;constructor&quot; > </bean> <bean id=&quot;transactionInterceptor&quot; class=&quot;org...TransactionInterceptor&quot; autowire =&quot;byType&quot;> </bean> <bean id=&quot;transactionAttributeSource&quot; class=&quot;org...AttributesTransactionAttributeSource&quot; autowire =&quot;constructor&quot;> </bean> <bean id=&quot;attributes&quot; class=&quot;org...CommonsAttributes&quot; /> Caches metadata from classes Generic autoproxy support Applies transaction using transactionManager Invokes interceptor based on attributes
  • 25.
  • 26.
    Data Access DAOsupport provides pluggable framework for persistence Currently supports JDBC, Hibernate, JDO, and iBatis Defines consistent exception hierarchy (based on RuntimeException) Provides abstract “Support” classes for each technology Template methods define specific queries
  • 27.
    Hibernate DAO Examplepublic class ReservationDaoImpl extends HibernateDaoSupport implements ReservationDao { public Reservation getReservation (Long orderId) { return (Reservation)getHibernateTemplate().load(Reservation .class, orderId); } public void saveReservation (Reservation r) { getHibernateTemplate().saveOrUpdate(r); } public void remove(Reservation Reservation) { getHibernateTemplate().delete(r); }
  • 28.
    Hibernate DAO (cont’d)public Reservation[] findReservations(Room room) { List list = getHibernateTemplate().find( &quot;from Reservation reservation “ + “ where reservation.resource =? “ + “ order by reservation.start&quot;, instrument); return (Reservation[]) list.toArray(new Reservation[list.size()]);
  • 29.
    Hibernate DAO (cont’d)public Reservation[] findReservations(final DateRange range) { final HibernateTemplate template = getHibernateTemplate(); List list = (List) template.execute(new HibernateCallback() { public Object doInHibernate(Session session) { Query query = session.createQuery( &quot;from Reservation r “ + “ where r.start > :rangeStart and r.start < :rangeEnd “); query.setDate(&quot;rangeStart&quot;, range.getStartDate() query.setDate(&quot;rangeEnd&quot;, range.getEndDate()) return query.list(); } }); return (Reservation[]) list.toArray(new Reservation[list.size()]); } }
  • 30.
    Hibernate Example <beanid=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate.LocalSessionFactoryBean&quot;> <property name=&quot;dataSource&quot;><ref bean=&quot;dataSource&quot;/></property> <property name=&quot;mappingResources&quot;> <list> <value>com/jensenp/Reservation/Room.hbm.xml</value> <value>com/jensenp/Reservation/Reservation.hbm.xml</value> <value>com/jensenp/Reservation/Resource.hbm.xml</value> </list> </property> <property name=&quot;hibernateProperties&quot;> <props> <prop key=&quot;hibernate.dialect&quot;>${hibernate.dialect}</prop> <prop key=&quot;hibernate.hbm2ddl.auto&quot;>${hibernate.hbm2ddl.auto} </prop> <prop key=&quot;hibernate.show_sql&quot;>${hibernate.show_sql}</prop> </props> </property> </bean> <bean id=“reservationDao&quot; class=&quot;com.jensenp.Reservation.ReservationDaoImpl&quot;> <property name=&quot;sessionFactory&quot;><ref bean=&quot;sessionFactory&quot;/> </property> </bean>
  • 31.
    JDBC Support JDBCTemplateprovides Translation of SQLExceptions to more meaningful Spring Runtime exceptions Integrates thread-specific transactions MappingSQLQuery simplifies mapping of ResultSets to Java objects
  • 32.
  • 33.
    DispatcherServlet The DispatcherServletis the Spring Front Controller Initializes WebApplicationContext Uses /WEB-INF/[servlet-name]-servlet.xml by default WebApplicationContext is bound into ServletContext
  • 34.
    DispatcherServlet Configuration HandlerMappingRouting of requests to handlers HandlerAdapter Adapts to handler interface. Default utilizes Controller s HandlerExceptionResolver Maps exceptions to error pages Similar to standard Servlet, but more flexible ViewResolver Maps symbolic name to view
  • 35.
    Dispatcher Servlet ConfigurationMultipartResolver Handling of file upload LocaleResolver Default uses HTTP accept header, cookie, or session
  • 36.
    Controllers Controller interfacedefines one method ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception ModelAndView consists of a view identifier and a Map of model data
  • 37.
    Controller Implementations CommandControllersbind parameters to data objects AbstractCommandController AbstractFormController SimpleFormController WizardFormController
  • 38.
    References Spring’s homepage:http://www.springframework.org “ Introducing the Spring Framework” by Rod Johnson: http://theserverside.com/news/thread.jsp?thread_id=21893 “ Inversion of control containers and dependency injection” by Martin Fowler: http://www.martinfowler.com/articles/injection.html AOP Alliance: http://aopalliance.sourceforge.net

Editor's Notes

  • #28 Template closures JDBC support also provided