Spring Presentation

74
Spring Overview Spring Overview Santosh Kothapalli Santosh Kothapalli

Transcript of Spring Presentation

Page 1: Spring Presentation

Spring OverviewSpring Overview

Santosh KothapalliSantosh Kothapalli

Page 2: Spring Presentation

Spring OriginSpring Origin

Created by Rod JohnsonCreated by Rod Johnson Based on “Expert one-on-one J2EE Design Based on “Expert one-on-one J2EE Design

and Development”and Development” Currently on version 3.0.xCurrently on version 3.0.x

Page 3: Spring Presentation

Spring MissionSpring Mission

J2EE should be easier to use J2EE should be easier to use It is best to program to interfaces, rather than classes. Spring reduces the It is best to program to interfaces, rather than classes. Spring reduces the

complexity cost of using interfaces to zero. complexity cost of using interfaces to zero. JavaBeans offer a great way of configuring applications. JavaBeans offer a great way of configuring applications. OO design is more important than any implementation technology, such as OO design is more important than any implementation technology, such as

J2EE. J2EE. Checked exceptions are overused in Java. A platform shouldn't force you Checked exceptions are overused in Java. A platform shouldn't force you

to catch exceptions you're unlikely to be able to recover from. to catch exceptions you're unlikely to be able to recover from. Testability is essential, and a platform such as Spring should help make Testability is essential, and a platform such as Spring should help make

your code easier to testyour code easier to test

Page 4: Spring Presentation

Why Use Spring?Why Use Spring?

Wiring of components (Dependency Injection)Wiring of components (Dependency Injection) Promotes/simplifies decoupling, design to interfaces, Promotes/simplifies decoupling, design to interfaces,

TDDTDD

Declarative programming without J2EEDeclarative programming without J2EE Easily configured aspects, esp. transaction supportEasily configured aspects, esp. transaction support

Simplify use of popular technologiesSimplify use of popular technologies Abstractions insulate application from specifics, Abstractions insulate application from specifics,

eliminate redundant code, and handle common error eliminate redundant code, and handle common error conditionsconditions

Underlying technology specifics still accessible Underlying technology specifics still accessible (closures)(closures)

Page 5: Spring Presentation

Spring FeaturesSpring Features The most complete lightweight containerThe most complete lightweight container, providing centralized, automated configuration , providing centralized, automated configuration

and wiring of your application objects. The container is and wiring of your application objects. The container is non-invasivenon-invasive, capable of assembling , capable of assembling a complex system from a set of loosely-coupled components (POJOs) in a consistent and 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 transparent fashion. The container brings agility and leverage, and improves application testability and scalability by allowing software components to be first developed and tested 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).in isolation, then scaled up for deployment in any environment (J2SE or J2EE).

A common abstraction layer for transaction managementA common abstraction layer for transaction management, allowing for pluggable , allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE environments.environments.

A JDBC abstraction layerA JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the 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 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 JDBC again. The JDBC-oriented exceptions comply to Spring's generic DAO exception hierarchy.hierarchy.

Page 6: Spring Presentation

Spring FeaturesSpring Features Integration with Toplink, Hibernate, JDO, and iBATIS SQL MapsIntegration with Toplink, Hibernate, JDO, and iBATIS SQL Maps : in terms of : in terms of

resource holders, DAO implementation support, and transaction strategies. First-resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply to Spring's generic typical Hibernate integration issues. All of these comply to Spring's generic transaction and DAO exception hierarchies.transaction and DAO exception hierarchies.

AOP functionality, fully integrated into Spring configuration management.AOP functionality, fully integrated into Spring configuration management. You can AOP-enable any object managed by Spring, adding aspects such as You can AOP-enable any object managed by Spring, adding aspects such as declarative transaction management. With Spring, you can have declarative declarative transaction management. With Spring, you can have declarative transaction management without EJB... even without JTA, if you're using a single transaction management without EJB... even without JTA, if you're using a single database in Tomcat or another web container without JTA support.database in Tomcat or another web container without JTA support.

A flexible MVC web application frameworkA flexible MVC web application framework , built on core Spring functionality. , built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web tier based on any other web Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry. MVC framework, like Struts, WebWork, or Tapestry.

Page 7: Spring Presentation

Benefits of Spring over other Benefits of Spring over other frameworksframeworks

Spring provides a very clean division between controllers, JavaBean Spring provides a very clean division between controllers, JavaBean models, and viewsmodels, and views

Spring has layered architecture. Use what you need and leave you don't Spring has layered architecture. Use what you need and leave you don't need now. need now.

Spring has a well defined interface to business layer Spring has a well defined interface to business layer

Spring Enables POJO Programming. There is no behind the scene magic Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability. here. POJO programming enables continuous integration and testability.

Dependency Injection and Inversion of Control Simplifies JDBC Dependency Injection and Inversion of Control Simplifies JDBC

Open source and no vendor lock-in. Open source and no vendor lock-in.

Page 8: Spring Presentation

Spring FrameworkSpring Framework

Page 9: Spring Presentation

Spring ApplicationSpring Application

Page 10: Spring Presentation

Spring Dependency InjectionSpring Dependency Injection Inversion of Control (IoC)Inversion of Control (IoC) ““Hollywood Principle”Hollywood Principle”

Don't call me, I'll call youDon't call me, I'll call you ““Container” resolves (injects) dependencies of components by setting Container” resolves (injects) dependencies of components by setting

implementation object (push)implementation object (push) As opposed to component instantiating or Service Locator pattern where As opposed to component instantiating or Service Locator pattern where

component locates implementation (pull)component locates implementation (pull) Martin Fowler calls Dependency InjectionMartin Fowler calls Dependency Injection

Page 11: Spring Presentation

Dependency Injection VariantsDependency Injection Variants Variations on dependency injectionVariations on dependency injection

Interface based (Avalon)Interface based (Avalon) Constructor-based (PicoContainer, Spring)Constructor-based (PicoContainer, Spring) Setter-based (Spring)Setter-based (Spring)

BeanFactory provides configuration framework to initialize and “wire” BeanFactory provides configuration framework to initialize and “wire” JavaBeansJavaBeans

org.springframework.beans and org.springframework.contextorg.springframework.beans and org.springframework.context Typically use the XmlBeanFactory, employing XML configuration filesTypically use the XmlBeanFactory, employing XML configuration files

Page 12: Spring Presentation

Dependency Injection (cont'd)Dependency Injection (cont'd)

BeanFactory configured components need have no Spring BeanFactory configured components need have no Spring dependenciesdependencies

Simple JavaBeansSimple JavaBeans Beans are singletons by defaultBeans are singletons by default Properties may be simple values or references to other beansProperties may be simple values or references to other beans Built-in support for defining Lists, Maps, Sets, and Properties collection Built-in support for defining Lists, Maps, Sets, and Properties collection

types. types. Custom PropertyEditors may be defined to convert string values to Custom PropertyEditors may be defined to convert string values to

other, arbitrary types.other, arbitrary types.

Page 13: Spring Presentation

XmlBeanFactory ExampleXmlBeanFactory Example

Property and constructor based IoCProperty 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>

<bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <constructor-arg><ref bean="yetAnotherBean"/></constructor-arg> <constructor-arg><value>1</value></constructor-arg></bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/><bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

Page 14: Spring Presentation

Bean CreationBean Creation

Direct instantiationDirect instantiation <bean id=“beanId” class=“className”><bean id=“beanId” class=“className”>

BeanFactory instantiationBeanFactory instantiation Same syntax but class is subclass of BeanFactorySame syntax but class is subclass of BeanFactory getObject() called to obtain BeangetObject() called to obtain Bean

Static FactoryStatic Factory <bean id=“beanId” <bean id=“beanId” class=“className" factory-method=" class=“className" factory-method="

staticCreationMethod“>staticCreationMethod“>

Instance Factory MethodInstance Factory Method <bean id=“beanId” factory-bean=“existingBeanId" factory-<bean id=“beanId” factory-bean=“existingBeanId" factory-

method=“nonStaticCreationMethod"> method=“nonStaticCreationMethod">

Page 15: Spring Presentation

Bean CreationBean Creation Beans may be singletons or “prototypes”Beans may be singletons or “prototypes”

Attribute Attribute singleton=“false”singleton=“false” causes instantiation with each getBean() causes instantiation with each getBean() lookuplookup

Singleton is defaultSingleton is default XmlBeanFactory pre-instantiates singletonsXmlBeanFactory pre-instantiates singletons

May be overridden on per-instance basis by May be overridden on per-instance basis by lazy-init=“true”lazy-init=“true” Beans may also be marked abstract, allowing reuse of attribute values Beans may also be marked abstract, allowing reuse of attribute values

through inheritancethrough inheritance

Page 16: Spring Presentation

Autowiring PropertiesAutowiring Properties

Beans may be auto-wired (rather than using <ref>)Beans may be auto-wired (rather than using <ref>) Per-bean attribute Per-bean attribute autowireautowire Explicit settings overrideExplicit settings override

autowire=“name”autowire=“name” Bean identifier matches property name Bean identifier matches property name

autowire=“type”autowire=“type” Type matches other defined beanType matches other defined bean

autowire=”constructor”autowire=”constructor” Match constructor argument typesMatch constructor argument types

autowire=”autodetect”autowire=”autodetect” Attempt by constructor, otherwise “type”Attempt by constructor, otherwise “type”

Page 17: Spring Presentation

Dependency CheckingDependency Checking

Ensures properties are definedEnsures properties are defined Per-bean attribute Per-bean attribute dependency-checkdependency-check None required by defaultNone required by default Verifies autowiring succeededVerifies autowiring succeeded

““simple”simple” all but collaboratorsall but collaborators

““object”object” collaborators onlycollaborators only

““all”all” Collaborators, primitive types, and collectionsCollaborators, primitive types, and collections

Page 18: Spring Presentation

Lifecycle CustomizationLifecycle Customization Can define init method called after properties setCan define init method called after properties set

init-method=”<method-name>”init-method=”<method-name>” Can define destroy method as shutdown hookCan define destroy method as shutdown hook

destroy-method=”<method-name>”destroy-method=”<method-name>” May alternatively implement InitializingBean and/or DisposableBeanMay alternatively implement InitializingBean and/or DisposableBean

At cost of Spring dependencyAt cost of Spring dependency

Page 19: Spring Presentation

BeanFactory MiscellanyBeanFactory Miscellany BeanFactoryAware interface provides BeanFactory for beanBeanFactoryAware interface provides BeanFactory for bean

setBeanFactory(BeanFactory)setBeanFactory(BeanFactory) BeanNameAware interface provides bean nameBeanNameAware interface provides bean name

setBeanName(String)setBeanName(String) FactoryBean for beans which are themselves factoriesFactoryBean for beans which are themselves factories

Object getObject()Object getObject() Boolean isSingleton()Boolean isSingleton() Class getObjectType()Class getObjectType()

Page 20: Spring Presentation

BeanFactory UsageBeanFactory UsageInputStream is = new FileInputStream("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(is);MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”);

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”);

OR

Page 21: Spring Presentation

ApplicationContextApplicationContext

Extends functionality of BeanFactoryExtends functionality of BeanFactory Pre-instantiates singleton beansPre-instantiates singleton beans Detects and registers Detects and registers BeanPostProcessorBeanPostProcessors and s and

BeanFactoryPostProcessorBeanFactoryPostProcessorss Supports nesting of contextsSupports nesting of contexts ApplicationListenerApplicationListener and and ApplicationEventsApplicationEvents

Initialized and closed predefinedInitialized and closed predefined Custom may be createdCustom may be created

MessageSourceMessageSource provides i18n messaging provides i18n messaging <bean id=”messageSource” <bean id=”messageSource”

class=”...ResourceBundleMessageSource”/>class=”...ResourceBundleMessageSource”/> Contains list of bundle base namesContains list of bundle base names

Page 22: Spring Presentation

Web InitializationWeb Initialization Web applications may use ContextLoaderListener to initialize SpringWeb applications may use ContextLoaderListener to initialize Spring

<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>

web.xml

Automatically done by Spring DispatcherServlet

Page 23: Spring Presentation

Specialized BeansSpecialized Beans MethodInvokingFactoryBeanMethodInvokingFactoryBean

Invokes method on registered beans or any static methodsInvokes method on registered beans or any static methods Stores return valueStores return value

SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocatorSingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator Useful for sharing BeanFactoriesUseful for sharing BeanFactories Eliminate duplication of beans in multiple similar factories or contextsEliminate duplication of beans in multiple similar factories or contexts

Page 24: Spring Presentation

ApplicationContext ApplicationContext customizationcustomization

Defined beans inheriting from Defined beans inheriting from BeanFactoryPostProcessorBeanFactoryPostProcessor are detected and are detected and invokedinvoked

CustomEditorConfigurerCustomEditorConfigurer Registers custom Registers custom PropertyEditorPropertyEditors for converting configuration string s for converting configuration string

values to specific typesvalues to specific types AutoProxyCreatorsAutoProxyCreators

Wrap beans in proxies based on various criteria (name, metadata, etc)Wrap beans in proxies based on various criteria (name, metadata, etc) PropertyResourceConfigurerPropertyResourceConfigurer

• Sets from property file and/or system propertiesSets from property file and/or system properties

Page 25: Spring Presentation

ApplicationContext ExampleApplicationContext 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>

Page 26: Spring Presentation

Spring AOPSpring AOP

Page 27: Spring Presentation

AOP FundamentalsAOP Fundamentals

Aspect-oriented programming (AOP) provides for simplified application Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concernsof cross-cutting concerns

Transaction managementTransaction management SecuritySecurity LoggingLogging AuditingAuditing LockingLocking

AOP sometimes (partially) achieved via Decorators or ProxiesAOP sometimes (partially) achieved via Decorators or Proxies CORBA Portable InterceptorsCORBA Portable Interceptors Servlet FiltersServlet Filters

Page 28: Spring Presentation

AOP FundamentalsAOP Fundamentals

Aspect - Implementation of a cross-cutting concern. Aspect - Implementation of a cross-cutting concern. Spring Advisors or InterceptorsSpring Advisors or Interceptors

Joinpoint - Execution point to targetJoinpoint - Execution point to target Typically, methodsTypically, methods

Advice - Action taken at a particular joinpoint.Advice - Action taken at a particular joinpoint. Pointcut - A set of joinpoints specifying where advice should be applied Pointcut - A set of joinpoints specifying where advice should be applied

(e.g. Regular expression)(e.g. Regular expression) Introduction/Mixin - Adding methods or fields to an advised class.Introduction/Mixin - Adding methods or fields to an advised class. Weaving - Assembling aspects into advised objects.Weaving - Assembling aspects into advised objects.

Page 29: Spring Presentation

Spring AOPSpring AOP

Generally, applies aspects to beans using BeanFactoryGenerally, applies aspects to beans using BeanFactory Uses Dynamic Proxies if interface available otherwise CGLIBUses Dynamic Proxies if interface available otherwise CGLIB CGLIB creates derived class which proxies requestsCGLIB creates derived class which proxies requests

• Bean class may not be finalBean class may not be final Less capable than AspectJLess capable than AspectJ

does not have field interceptiondoes not have field interception only runtime weaving solution is availableonly runtime weaving solution is available Closer integration with AspectJ anticipatedCloser integration with AspectJ anticipated

Page 30: Spring Presentation

Spring PointcutsSpring Pointcuts Pointcut applicability to a class may be evaluated statically or Pointcut applicability to a class may be evaluated statically or

dynamicallydynamically Spring only creates proxies where necessarySpring only creates proxies where necessary

public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher();}

public interface ClassFilter { boolean matches(Class clazz);}

Page 31: Spring Presentation

Pointcuts (cont'd)Pointcuts (cont'd)

public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args);}

Pointcut may be statically or dynamically evaluated based on isRuntime()Pointcut may be statically or dynamically evaluated based on isRuntime() Abstract class StaticMethodMatcherPointcut requires override of 1Abstract class StaticMethodMatcherPointcut requires override of 1stst method method

onlyonly

Only called if isRuntime() == true

Page 32: Spring Presentation

Pointcuts (cont'd)Pointcuts (cont'd) Spring predefined pointcutsSpring predefined pointcuts

In org.springframework.aop.support packageIn org.springframework.aop.support package RegexpMethodPointcutRegexpMethodPointcut

Union of multiple regular expressionsUnion of multiple regular expressions Uses Jakarta ORO packageUses Jakarta ORO package

ControlFlowPointcutControlFlowPointcut Similar to AspectJ cflowSimilar to AspectJ cflow Applied if call stack includes specific class and, optionally, methodApplied if call stack includes specific class and, optionally, method

UnionPointcutUnionPointcut Merges pointcutsMerges pointcuts

Page 33: Spring Presentation

Spring AdviceSpring Advice Can have per-class or per-instance AdviceCan have per-class or per-instance Advice Spring provides several Advice typesSpring provides several Advice types Around AdviceAround Advice

• AOP Alliance compliantAOP Alliance compliant• Must call invocation.proceed() to call targetMust call invocation.proceed() to call target

public class MyAdvice implements AroundAdvice { Object invoke(MethodInvocation invocation) { // change arguments, start transaction, lock, etc. invocation.proceed(); // change return value, stop transaction, unlock,etc. }}

Page 34: Spring Presentation

Spring AdviceSpring Advice

MethodBeforeAdviceMethodBeforeAdvice void before(Method m, Object[] args, Object target)void before(Method m, Object[] args, Object target) Cannot alter return typeCannot alter return type

ThrowsAdviceThrowsAdvice Marker interfaceMarker interface Implementors define methods of form:Implementors define methods of form:

• afterThrowing([Method], [args], [target], subclassOfThrowable)afterThrowing([Method], [args], [target], subclassOfThrowable) AfterReturningAdviceAfterReturningAdvice

void afterReturning(Object returnValue, Method, m, Object[] args, void afterReturning(Object returnValue, Method, m, Object[] args, Object target)Object target)

Cannot modify return valueCannot modify return value

Page 35: Spring Presentation

Spring AdviceSpring Advice IntroductionInterceptor provides ability to define IntroductionInterceptor provides ability to define mixinsmixins

public class RollbackAdvice extends DelegatingIntroductionInterceptor implements RollbackSupport { Map map = new HashMap(); void rollback(Date date) { // rollback to state at given time }

public Object invoke(MethodInvocation invocation) { // record change and time of change }}

Page 36: Spring Presentation

Injecting AdviceInjecting Advice<bean id=“meetingTarget" class=“ex.DefaultMeeting“ singleton=“false”> <property name=“topic">Spring</property></bean>

<bean id="myAdvisor" class=“ex.RollbackAdvice" singleton=”false”></bean>

<bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor"></bean>

Page 37: Spring Presentation

Injecting Advice (cont'd)Injecting Advice (cont'd)

<bean id=“meeting" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>ex.Meeting</value> </property>

<property name="target"><ref local=“meetingTarget"/></property>

<property name="interceptorNames"> <list> <value>myAdvisor</value> <value>debugInterceptor</value> </list> </property></bean>

Advisors applied in order

All methodsusing CGLib if none defined

Page 38: Spring Presentation

AutoproxyingAutoproxying Autoproxy bean definitions automatically proxy selected beans. Autoproxy bean definitions automatically proxy selected beans. BeanNameAutoProxyCreatorBeanNameAutoProxyCreator

Adds listed advisors/interceptors to beans with names matching regular Adds listed advisors/interceptors to beans with names matching regular expressionexpression

DefaultAdvisorAutoProxyCreatorDefaultAdvisorAutoProxyCreator Generic autoproxy infrastructure supportGeneric autoproxy infrastructure support Applies all advisors defined in the context to all beans, proxying Applies all advisors defined in the context to all beans, proxying

appropriatelyappropriately

Page 39: Spring Presentation

Metadata supportMetadata support

Spring supports obtaining meta data Object attributes at class, method, Spring supports obtaining meta data Object attributes at class, method, and field leveland field level

Not yet argument level (as JSR-175)Not yet argument level (as JSR-175) Currently supports Jakarta Commons AttributesCurrently supports Jakarta Commons Attributes Support for JSR-175 in workSupport for JSR-175 in work Metadata support provided via Metadata support provided via AttributesAttributes interface interface

Amenable to mocking unlike JDK reflection and Commons static Amenable to mocking unlike JDK reflection and Commons static methodsmethods

Page 40: Spring Presentation

Metadata autoproxyingMetadata autoproxying

Configuration of autoproxying based on metadata attributes simplifies Configuration of autoproxying based on metadata attributes simplifies configurationconfiguration

Define custom attribute classDefine custom attribute class Define Advisor with pointcut based on custom attributeDefine Advisor with pointcut based on custom attribute Add Advisor in ApplicationContext with autoproxyAdd Advisor in ApplicationContext with autoproxy

ExamplesExamples Transaction AttributesTransaction Attributes Security AttributesSecurity Attributes PoolingPooling Mapping of controllers to URLsMapping of controllers to URLs

Page 41: Spring Presentation

TransactionsTransactions

Page 42: Spring Presentation

AOP TransactionsAOP Transactions Spring provides AOP support for declarative transactionsSpring provides AOP support for declarative transactions Delegates to a PlatformTransactionManager instanceDelegates to a PlatformTransactionManager instance

DataSourceTransactionManagerDataSourceTransactionManager HibernateTransactionManagerHibernateTransactionManager JdoTransactionManagerJdoTransactionManager JtaTransactionManagerJtaTransactionManager

Page 43: Spring Presentation

Transaction ConfigurationTransaction 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>

Page 44: Spring Presentation

Declarative TransactionsDeclarative Transactions Declarative transactional support can be added to any bean by using Declarative transactional support can be added to any bean by using

TransactionProxyFactoryBeanTransactionProxyFactoryBean Similar to EJB, transaction attributes may be defined on a per-method basisSimilar to EJB, transaction attributes may be defined on a per-method basis Also allows definition of pre- and post- interceptors (e.g. for security)Also allows definition of pre- and post- interceptors (e.g. for security)

Page 45: Spring Presentation

Injecting Transaction SupportInjecting 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>

Declarative transaction support for single bean

Page 46: Spring Presentation

Transaction AutoproxyTransaction Autoproxy

<bean id="autoproxy" class="org...DefaultAdvisorAutoProxyCreator"></bean>

<bean id="transactionAdvisor" class="org...TransactionAttributeSourceAdvisor" autowire="constructor" ></bean>

<bean id="transactionInterceptor" class="org...TransactionInterceptor" autowire="byType"> </bean>

<bean id="transactionAttributeSource" class="org...AttributesTransactionAttributeSource" autowire="constructor"></bean>

<bean id="attributes" class="org...CommonsAttributes"/>

Caches metadatafrom classes

Generic autoproxysupport

Applies transactionusing transactionManager

Invokes interceptorbased on attributes

Page 47: Spring Presentation

Data AccessData Access

Page 48: Spring Presentation

Data AccessData Access DAO support provides pluggable framework for persistenceDAO support provides pluggable framework for persistence Currently supports JDBC, Hibernate, JDO, and iBatisCurrently supports JDBC, Hibernate, JDO, and iBatis Defines consistent exception hierarchy (based on RuntimeException)Defines consistent exception hierarchy (based on RuntimeException) Provides abstract “Support” classes for each technologyProvides abstract “Support” classes for each technology

Template methods define specific queriesTemplate methods define specific queries

Page 49: Spring Presentation

Hibernate DAO ExampleHibernate 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); }

Page 50: Spring Presentation

Hibernate DAO (cont’d)Hibernate DAO (cont’d)

public Reservation[] findReservations(Room room) { List list = getHibernateTemplate().find( "from Reservation reservation “ + “ where reservation.resource =? “ + “ order by reservation.start", instrument); return (Reservation[]) list.toArray(new Reservation[list.size()]);

Page 51: Spring Presentation

Hibernate DAO (cont’d)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( "from Reservation r “ + “ where r.start > :rangeStart and r.start < :rangeEnd “); query.setDate("rangeStart", range.getStartDate() query.setDate("rangeEnd", range.getEndDate()) return query.list(); } }); return (Reservation[]) list.toArray(new Reservation[list.size()]); }}

Page 52: Spring Presentation

Hibernate ExampleHibernate Example<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource"><ref bean="dataSource"/></property> <property name="mappingResources"> <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="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> </props> </property> </bean>

<bean id=“reservationDao" class="com.jensenp.Reservation.ReservationDaoImpl"> <property name="sessionFactory"><ref bean="sessionFactory"/> </property> </bean>

Page 53: Spring Presentation

JDBC SupportJDBC Support JDBCTemplate providesJDBCTemplate provides

Translation of SQLExceptions to more meaningful Spring Runtime Translation of SQLExceptions to more meaningful Spring Runtime exceptionsexceptions

Integrates thread-specific transactionsIntegrates thread-specific transactions MappingSQLQuery simplifies mapping of ResultSets to Java objectsMappingSQLQuery simplifies mapping of ResultSets to Java objects

Page 54: Spring Presentation

Web FrameworkWeb Framework

Page 55: Spring Presentation

DispatcherServletDispatcherServlet The DispatcherServlet is the Spring Front ControllerThe DispatcherServlet is the Spring Front Controller Initializes WebApplicationContextInitializes WebApplicationContext Uses Uses /WEB-INF/[servlet-name]-servlet.xml/WEB-INF/[servlet-name]-servlet.xml by default by default WebApplicationContext is bound into ServletContextWebApplicationContext is bound into ServletContext

Page 56: Spring Presentation

DispatcherServlet ConfigurationDispatcherServlet Configuration HandlerMappingHandlerMapping

Routing of requests to handlersRouting of requests to handlers HandlerAdapterHandlerAdapter

Adapts to handler interface. Default utilizes Adapts to handler interface. Default utilizes ControllerControllerss HandlerExceptionResolverHandlerExceptionResolver

Maps exceptions to error pagesMaps exceptions to error pages Similar to standard Servlet, but more flexibleSimilar to standard Servlet, but more flexible

ViewResolverViewResolver Maps symbolic name to viewMaps symbolic name to view

Page 57: Spring Presentation

Dispatcher Servlet ConfigurationDispatcher Servlet Configuration MultipartResolverMultipartResolver

Handling of file uploadHandling of file upload LocaleResolverLocaleResolver

Default uses HTTP accept header, cookie, or sessionDefault uses HTTP accept header, cookie, or session

Page 58: Spring Presentation

ControllersControllers Controller interface defines one methodController interface defines one method

ModelAndView handleRequest(HttpServletRequest req, ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ExceptionHttpServletResponse resp) throws Exception

ModelAndView consists of a view identifier and a Map of model dataModelAndView consists of a view identifier and a Map of model data

Page 59: Spring Presentation

Controller ImplementationsController Implementations CommandControllers bind parameters to data objectsCommandControllers bind parameters to data objects AbstractCommandControllerAbstractCommandController AbstractFormControllerAbstractFormController SimpleFormControllerSimpleFormController WizardFormControllerWizardFormController

Page 60: Spring Presentation

Creating Spring IOC Creating Spring IOC ApplicationApplication

Page 61: Spring Presentation

Hello World Application using EclipseHello World Application using Eclipse

Create new Java Project , File->New->Java Create new Java Project , File->New->Java ProjectProject

Page 62: Spring Presentation

Contd.Contd. Give project name as HelloWorld and click FinishGive project name as HelloWorld and click Finish

Page 63: Spring Presentation

Contd.Contd. Right Click on the Project and Add Spring Capabilities, which add all the Right Click on the Project and Add Spring Capabilities, which add all the

resources required for executing the spring applicationresources required for executing the spring application

Page 64: Spring Presentation

Contd.Contd.

Click NextClick Next

Page 65: Spring Presentation

Contd.Contd.

This adds the spring configuration file to the HelloWorld Project, Click This adds the spring configuration file to the HelloWorld Project, Click FinishFinish

Page 66: Spring Presentation

Contd.Contd.

On Successful creation of spring project you see applicationContext.xml On Successful creation of spring project you see applicationContext.xml added to the HelloWorld project , similar to below screen shot in the added to the HelloWorld project , similar to below screen shot in the package explorer of Eclipse IDEpackage explorer of Eclipse IDE

Page 67: Spring Presentation

Contd.Contd.Create a java class called HelloWorld , by right clicking on the src directory of Create a java class called HelloWorld , by right clicking on the src directory of

the projectthe project

New -> Class New -> Class

Page 68: Spring Presentation

ContdContd

Give the package and class name and click FinishGive the package and class name and click Finish

Page 69: Spring Presentation

Contd.Contd.

HelloWorld.javaHelloWorld.java

Page 70: Spring Presentation

Contd.Contd.

applicationContext.xmlapplicationContext.xml

Page 71: Spring Presentation

Running the ApplicationRunning the Application

Right click on the HelloWorld.java and Run As , Java ApplicationRight click on the HelloWorld.java and Run As , Java Application

Page 72: Spring Presentation

OutputOutput

Successful execution will display the value that is set as value in Successful execution will display the value that is set as value in applicationContext.xmlapplicationContext.xml

Page 73: Spring Presentation

ReferencesReferences

Spring’s homepage: http://www.springframework.orgSpring’s homepage: http://www.springframework.org ““Introducing the Spring Framework” by Rod Johnson: Introducing the Spring Framework” by Rod Johnson:

http://theserverside.com/news/thread.jsp?thread_id=21893http://theserverside.com/news/thread.jsp?thread_id=21893 ““Inversion of control containers and dependency injection” by Martin Fowler: Inversion of control containers and dependency injection” by Martin Fowler:

http://www.martinfowler.com/articles/injection.htmlhttp://www.martinfowler.com/articles/injection.html AOP Alliance: http://aopalliance.sourceforge.netAOP Alliance: http://aopalliance.sourceforge.net

Page 74: Spring Presentation

Thank YouThank You