Professional Documents
Culture Documents
Santosh Kothapalli
Spring Origin
Created by Rod Johnson
Based on “Expert one-on-one J2EE Design
and Development”
Currently on version 3.0.x
Spring Mission
J2EE should be easier to use
It is best to program to interfaces, rather than classes. Spring reduces the
complexity cost of using interfaces to zero.
JavaBeans offer a great way of configuring applications.
OO design is more important than any implementation technology, such as
J2EE.
Checked exceptions are overused in Java. A platform shouldn't force you
to catch exceptions you're unlikely to be able to recover from.
Testability is essential, and a platform such as Spring should help make
your code easier to test
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)
Spring Features
The most complete lightweight container, providing centralized,
automated configuration and wiring of your application objects. The
container is non-invasive, capable of assembling a complex system from a
set of loosely-coupled components (POJOs) in a consistent and
transparent fashion. The container brings agility and leverage, and
improves application testability and scalability by allowing software
components to be first developed and tested in isolation, then scaled up for
deployment in any environment (J2SE or J2EE).
Spring has layered architecture. Use what you need and leave you don't
need now.
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>
PropertyResourceConfigurer
• Sets from property file and/or system properties
ApplicationContext Example
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>database.properties</value></property>
</bean>
<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
UnionPointcut
Merges pointcuts
Spring Advice
Can have per-class or per-instance Advice
Spring provides several Advice types
Around Advice
• AOP Alliance compliant
• Must call invocation.proceed() to call target
<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>
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" 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
Click Next
Contd.
This adds the spring configuration file to the HelloWorld Project, Click
Finish
Contd.
HelloWorld.java
Contd.
applicationContext.xml
Running the Application