Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Spring Overview
“Lightweight Container”
Very loosely coupled
Components widely reusable and separately
packaged
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?
Not an all-or-nothing solution
Extremely modular and flexible
Well designed
Easy to extend
Many reusable classes
Spring Framework
Spring Application
Spring Dependency Injection
Inversion of Control (IoC)
“Hollywood Principle”
Don't call me, I'll call you
“Container” resolves (injects) dependencies of
components by setting implementation object (push)
As opposed to component instantiating or Service
Locator pattern where component locates
implementation (pull)
Martin Fowler calls Dependency Injection
Dependency Injection Variants
Variations on dependency injection
Interface based (Avalon)
Constructor-based (PicoContainer, Spring)
Setter-based (Spring)
BeanFactory provides configuration framework to
initialize and “wire” JavaBeans
org.springframework.beans and
org.springframework.context
Typically use the XmlBeanFactory, employing XML
configuration files
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.
XmlBeanFactory Example
Property and constructor based IoC
<bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty">1</property>
</bean>
OR
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”);
ApplicationContext
Extends functionality of BeanFactory
Pre-instantiates singleton beans
Detects and registers BeanPostProcessors and
BeanFactoryPostProcessors
Supports nesting of contexts
ApplicationListener and ApplicationEvents
Initialized and closed predefined
Custom may be created
MessageSource provides i18n messaging
<bean id=”messageSource”
class=”...ResourceBundleMessageSource”/>
Contains list of bundle base names
Web Initialization
Web applications may use
ContextLoaderListener to initialize Spring
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${database.connection.driver_class}</value>
</property>
<property name="url">
<value>${database.connection.url}</value>
</property>
</bean>
Spring AOP
AOP Fundamentals
Aspect-oriented programming (AOP) provides for
simplified application of cross-cutting concerns
Transaction management
Security
Logging
Auditing
Locking
AOP sometimes (partially) achieved via Decorators or
Proxies
CORBA Portable Interceptors
Servlet Filters
AOP Fundamentals
Aspect - Implementation of a cross-cutting concern.
Spring Advisors or Interceptors
Joinpoint - Execution point to target
Typically, methods
Advice - Action taken at a particular joinpoint.
Pointcut - A set of joinpoints specifying where advice
should be applied (e.g. Regular expression)
Introduction/Mixin - Adding methods or fields to an
advised class.
Weaving - Assembling aspects into advised objects.
Spring AOP
Generally, applies aspects to beans using BeanFactory
Uses Dynamic Proxies if interface available
otherwise CGLIB
CGLIB creates derived class which proxies requests
Bean class may not be final
<bean id="debugInterceptor"
class="org.springframework.aop.interceptor.DebugInterceptor">
</bean>
Injecting Advice (cont'd)
<bean id=“meeting"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"> All methods
<value>ex.Meeting</value> using CGLib
</property> if none defined
<property name="target"><ref local=“meetingTarget"/></property>
<property name="interceptorNames">
<list> Advisors applied in order
<value>myAdvisor</value>
<value>debugInterceptor</value>
</list>
</property>
</bean>
Transactions
AOP Transactions
Spring provides AOP support for declarative
transactions
Delegates to a PlatformTransactionManager
instance
DataSourceTransactionManager
HibernateTransactionManager
JdoTransactionManager
JtaTransactionManager
Transaction Configuration
<bean id="sessionFactory"
class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="dataSource"/></property>
<property name="mappingResources">
<list>
<value>com/../model/*.hbm.xml</value>
</list>
</property>
</bean>
<bean id="transactionManager”
class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</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
Declarative transaction support for single bean
<bean id=“reservationService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target"><ref local=“reservationServiceTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key=“reserveRoom*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
Transaction Autoproxy
<bean id="autoproxy" Generic autoproxy
class="org...DefaultAdvisorAutoProxyCreator">
</bean> support
<bean id="transactionAdvisor"
class="org...TransactionAttributeSourceAdvisor" Invokes interceptor
autowire="constructor" > based on attributes
</bean>
<bean id="attributes"
class="org...CommonsAttributes"
/>
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);
}
<bean id=“reservationDao"
class="com.jensenp.Reservation.ReservationDaoImpl">
<property name="sessionFactory"><ref bean="sessionFactory"/>
</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 Controllers
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