SlideShare a Scribd company logo
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

More Related Content

PPTX
The java server pages
ODP
Developing and testing ajax components
PPT
Boston Computing Review - Java Server Pages
PPT
Lecture 5 - Comm Lab: Web @ ITP
PPT
Rich faces
PDF
Testing untestable code - DPC10
PPT
What's new and exciting with JSF 2.0
The java server pages
Developing and testing ajax components
Boston Computing Review - Java Server Pages
Lecture 5 - Comm Lab: Web @ ITP
Rich faces
Testing untestable code - DPC10
What's new and exciting with JSF 2.0

What's hot (17)

PDF
Exception Handling: Designing Robust Software in Ruby
PDF
Testing untestable Code - PFCongres 2010
PPT
Spring training
PDF
C++ boot camp part 1/2
PDF
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
PPT
Java 7 new features
DOC
Introduction to java script
PDF
Javascript Best Practices
PDF
Wt unit 2 ppts client side technology
PDF
Wt unit 4 server side technology-2
PPTX
Introduction to java script
PDF
Real world dependency injection - DPC10
PDF
Wt unit 5 client &amp; server side framework
PPT
my test
PPT
hibernate with JPA
PPTX
Random Ruby Tips - Ruby Meetup 27 Jun 2018
PDF
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
Exception Handling: Designing Robust Software in Ruby
Testing untestable Code - PFCongres 2010
Spring training
C++ boot camp part 1/2
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Java 7 new features
Introduction to java script
Javascript Best Practices
Wt unit 2 ppts client side technology
Wt unit 4 server side technology-2
Introduction to java script
Real world dependency injection - DPC10
Wt unit 5 client &amp; server side framework
my test
hibernate with JPA
Random Ruby Tips - Ruby Meetup 27 Jun 2018
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
Ad

Similar to Spring overview (20)

PDF
Spring framework
PPT
Tu1 1 5l
PPT
Developing Transactional JEE Apps With Spring
PPT
Spring Framework
PPT
Hybernat and structs, spring classes in mumbai
PDF
Spring 2
PPT
Spring talk111204
PPTX
สปริงเฟรมเวิร์ค4.1
PPTX
Spring IOC and DAO
PPT
SpringIntroductionpresentationoverintroduction.ppt
PPT
Spring introduction
PPTX
Spring Basics
PPT
Spring Framework
PPTX
Spring 1 day program
PPT
Os Johnson
PPT
Spring
PPT
Spring talk111204
PPT
Spring AOP @ DevClub.eu
PPTX
Spring from a to Z
PPTX
Introduction to Spring
Spring framework
Tu1 1 5l
Developing Transactional JEE Apps With Spring
Spring Framework
Hybernat and structs, spring classes in mumbai
Spring 2
Spring talk111204
สปริงเฟรมเวิร์ค4.1
Spring IOC and DAO
SpringIntroductionpresentationoverintroduction.ppt
Spring introduction
Spring Basics
Spring Framework
Spring 1 day program
Os Johnson
Spring
Spring talk111204
Spring AOP @ DevClub.eu
Spring from a to Z
Introduction to Spring
Ad

More from Dhaval Shah (7)

PPTX
JVM memory management & Diagnostics
PPTX
Transaction boundaries in Microservice Architecture
PPTX
Anatomy of Test Driven Development
PPTX
Microservice Architecture
PPT
OO design principles & heuristics
PPTX
Enterprise application performance - Understanding & Learnings
PPT
Spring Basics
JVM memory management & Diagnostics
Transaction boundaries in Microservice Architecture
Anatomy of Test Driven Development
Microservice Architecture
OO design principles & heuristics
Enterprise application performance - Understanding & Learnings
Spring Basics

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Digital-Transformation-Roadmap-for-Companies.pptx
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
Unlocking AI with Model Context Protocol (MCP)
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Programs and apps: productivity, graphics, security and other tools
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

Spring overview

  • 2. Contents Why? Overview DI/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 Lightweight Inversion of Control Aspect Oriented Container Framework
  • 7. 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
  • 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.
  • 14. AOP Fundamentals Aspect-oriented programming (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 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
  • 20. 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.
  • 21. 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>
  • 22. 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)
  • 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
  • 26. 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
  • 27. 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); }
  • 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 <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>
  • 31. 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
  • 33. DispatcherServlet The DispatcherServlet is the Spring Front Controller Initializes WebApplicationContext Uses /WEB-INF/[servlet-name]-servlet.xml by default WebApplicationContext is bound into ServletContext
  • 34. 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
  • 35. Dispatcher Servlet Configuration MultipartResolver Handling of file upload LocaleResolver Default uses HTTP accept header, cookie, or session
  • 36. 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
  • 37. Controller Implementations CommandControllers bind 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