Spring Presentation
Spring Presentation
Umesh Adhikari
Spring Origin
Created by Rod Johnson
Based on “Expert one-on-one J2EE Design and Development”
Currently on version 3.0.x
Spring Mission
A JDBC abstraction layer that offers a meaningful exception hierarchy (no more
pulling vendor codes out of SQLException), simplifies error handling, and
greatly reduces the amount of code you'll need to write. You'll never need to
write another finally block to use JDBC again. The JDBC-oriented exceptions
comply to Spring's generic DAO exception hierarchy.
Spring Features
Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps: in terms
of resource holders, DAO implementation support, and transaction strategies.
First-class Hibernate support with lots of IoC convenience features, addressing
many typical Hibernate integration issues. All of these comply to Spring's
generic transaction and DAO exception hierarchies.
Spring has layered architecture. Use what you need and leave you don't need
now.
Spring Enables POJO Programming. There is no behind the scene magic here.
POJO programming enables continuous integration and testability.
Direct instantiation
<bean id=“beanId” class=“className”>
BeanFactory instantiation
Same syntax but class is subclass of BeanFactory
getObject() called to obtain Bean
Static Factory
<bean id=“beanId” class=“className" factory-method="
staticCreationMethod“>
Instance Factory Method
<bean id=“beanId” factory-bean=“existingBeanId" factory-
method=“nonStaticCreationMethod">
Bean Creation
Beans may be singletons or “prototypes”
Attribute singleton=“false” causes instantiation with each getBean() lookup
Singleton is default
XmlBeanFactory pre-instantiates singletons
May be overridden on per-instance basis by lazy-init=“true”
Beans may also be marked abstract, allowing reuse of attribute values through
inheritance
Autowiring Properties
Beans may be auto-wired (rather than using <ref>)
Per-bean attribute autowire
Explicit settings override
autowire=“name”
Bean identifier matches property name
autowire=“type”
Type matches other defined bean
autowire=”constructor”
Match constructor argument types
autowire=”autodetect”
Attempt by constructor, otherwise “type”
Dependency Checking
Ensures properties are defined
Per-bean attribute dependency-check
None required by default
Verifies autowiring succeeded
“simple”
all but collaborators
“object”
collaborators only
“all”
Collaborators, primitive types, and collections
Lifecycle Customization
Can define init method called after properties set
init-method=”<method-name>”
Can define destroy method as shutdown hook
destroy-method=”<method-name>”
May alternatively implement InitializingBean and/or DisposableBean
At cost of Spring dependency
BeanFactory Miscellany
BeanFactoryAware interface provides BeanFactory for bean
setBeanFactory(BeanFactory)
BeanNameAware interface provides bean name
setBeanName(String)
FactoryBean for beans which are themselves factories
Object getObject()
Boolean isSingleton()
Class getObjectType()
BeanFactory Usage
InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”);
OR
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
Less capable than AspectJ
does not have field interception
only runtime weaving solution is available
Closer integration with AspectJ anticipated
Spring Pointcuts
Pointcut applicability to a class may be evaluated statically or dynamically
Spring only creates proxies where necessary
<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="interceptorNames">
<list>
<value>myAdvisor</value> Advisors applied in order
<value>debugInterceptor</value>
</list>
</property>
</bean>
Autoproxying
Autoproxy bean definitions automatically proxy selected beans.
BeanNameAutoProxyCreator
Adds listed advisors/interceptors to beans with names matching regular
expression
DefaultAdvisorAutoProxyCreator
Generic autoproxy infrastructure support
Applies all advisors defined in the context to all beans, proxying appropriately
Metadata support
Spring supports obtaining meta data Object attributes at class, method, and
field level
Not yet argument level (as JSR-175)
Currently supports Jakarta Commons Attributes
Support for JSR-175 in work
Metadata support provided via Attributes interface
Amenable to mocking unlike JDK reflection and Commons static methods
Metadata autoproxying
Configuration of autoproxying based on metadata attributes simplifies
configuration
Define custom attribute class
Define Advisor with pointcut based on custom attribute
Add Advisor in ApplicationContext with autoproxy
Examples
Transaction Attributes
Security Attributes
Pooling
Mapping of controllers to URLs
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
<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"
class="org...DefaultAdvisorAutoProxyCreator">
</bean>
Generic autoproxy
<bean id="transactionAdvisor"
support
class="org...TransactionAttributeSourceAdvisor"
autowire="constructor" >
</bean>
Invokes interceptor
<bean id="transactionInterceptor" based on attributes
class="org...TransactionInterceptor"
autowire="byType">
</bean> Applies transaction
using transactionManager
<bean id="transactionAttributeSource"
class="org...AttributesTransactionAttributeSource"
autowire="constructor"> Caches metadata
</bean> from classes
<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
<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
Creating Spring IOC
Application
Hello World Application using Eclipse
Create new Java Project , File->New->Java
Project
Contd.
Right Click on the Project and Add Spring Capabilities, which add all the
resources required for executing the spring application
Contd.
Click Next
Contd.
This adds the spring configuration file to the HelloWorld Project, Click Finish
Contd.
Create a java class called HelloWorld , by right clicking on the src directory of the
project
New -> Class
Contd
HelloWorld.java
Contd.
applicationContext.xml
Running the Application