springframework-120522023855-phpapp02

46
Introduction to the Introduction to the Spring Framework Spring Framework Spring is F = -kx (physics) One of 4 Seasons An Open-Source, Application Framework Ajit Ajit Koti Koti

description

Spring

Transcript of springframework-120522023855-phpapp02

Page 1: springframework-120522023855-phpapp02

Introduction to the Spring Introduction to the Spring FrameworkFramework

Spring is• F = -kx (physics)•„ One of 4 Seasons•„ An Open-Source, Application Framework

Ajit KotiAjit Koti

Page 2: springframework-120522023855-phpapp02

ReferencesReferences Spring’s homepage: http://www.springframework.org Spring documentation - http://www.springsource.org/documentation Spring API -

http://static.springframework.org/spring/docs/2.5.x/api/index.html Introduction to the Spring Framework 2.5, by Rod Johnson (Originator

of Spring) - http://www.theserverside.com/tt/articles/article.tss?l=IntrotoSpring25

“Inversion of control containers and dependency injection” by Martin Fowler: http://www.martinfowler.com/articles/injection.html

AOP Alliance: http://aopalliance.sourceforge.net

Page 3: springframework-120522023855-phpapp02

What is Spring?What is Spring? A Container Creates objects and makes them available to your application A Framework Provides an infrastructure of classes that make it easier to

accomplish tasks

Page 4: springframework-120522023855-phpapp02

What does Spring What does Spring provide?provide?

◦ Lightweight container and framework Most of your code will be unaware of the Spring

framework Use only the parts you of Spring you want

◦ Manages dependencies between your objects Encourages use of interfaces Lessens “coupling” between objects

◦ Cleaner separation of responsibilities Put logic that applies to many objects in one single

place Separate the class’s core responsibility from other

duties

Promotes Architectural choice – choose best of breed frameworks� Does not reinvent the wheel – O/R, logging, etc.�

Page 5: springframework-120522023855-phpapp02

Spring + J2EESpring + J2EESpring enables you to build applications from “plain old Java

objects” (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.

Examples of how you, as an application developer, can use the Spring platform advantage:

Make a Java method execute in a database transaction without having to deal with transaction APIs.

Make a local Java method a remote procedure without having to deal with remote APIs.

Make a local Java method a management operation without having to deal with JMX APIs.

Make a local Java method a message handler without having to deal with JMS APIs.

Page 6: springframework-120522023855-phpapp02

Overview of the Spring Overview of the Spring FrameworkFramework

Page 7: springframework-120522023855-phpapp02

Spring Framework ValuesSpring Framework Values � Non-invasive framework – code works outside framework,

minimal lock-in, easy migration Consistent model in any environment� Promotes code reuse and deferment of architectural decisions.� Facilitates OO code and good practices such as programming to �

interfaces Extraction of configuration to consistent xml model� Promotes Architectural choice – choose best of breed frameworks� Does not reinvent the wheel – O/R, logging, etc.�

Page 8: springframework-120522023855-phpapp02

Usage ScenariosUsage Scenarios

Page 9: springframework-120522023855-phpapp02

Inversion of Control (IoC)Inversion of Control (IoC) Dependency injection

◦ Beans define their dependencies through constructor arguments or properties

◦ The container provides the injection at runtime “Don’t talk to strangers” Also known as the Hollywood principle – “don’t call me I will call

you” Decouples object creators and locators from application logic Easy to maintain and reuse Testing is easier

Page 10: springframework-120522023855-phpapp02

Dependency InjectionDependency Injection

Variations on dependency injection•Constructor-based•Setter-based

Page 11: springframework-120522023855-phpapp02

Constructor-based dependency Constructor-based dependency injectioninjection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments

public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder

private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' a MovieFinder

public SimpleMovieLister(MovieFinder movieFinder) { this.movieFinder = movieFinder; }

}

<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <constructor-arg name=“movieFinder”><ref bean=“movieFinder”/></bean><bean id=“movieFinder” class=“example. MovieFinder”>

Page 12: springframework-120522023855-phpapp02

Setter-based dependency injectionSetter-based dependency injection Setter-based DI is accomplished by the container calling setter

methods on your beans after invoking a no-argument constructor or no-argumentstatic factory method to instantiate your bean.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder;

public SimpleMovieLister() { }

// a setter method so that the Spring container can 'inject' a MovieFinder public setMovieFinder (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }

<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <property name=“movieFinder”><ref bean=“movieFinder”/> </property></bean><bean id=“movieFinder” class=“example. MovieFinder”>

Page 13: springframework-120522023855-phpapp02

Abstract BeansAbstract Beans Allows definition of part of a bean which can be reused many times in

other bean definitions

The parent bean defines 2 values (name, age)

The child bean uses the parent age value (31)

The child bean overrides the parent name value (from parent-AZ to child-AZ)

Parent bean could not be injected, child could

<bean id="abstractBean" abstract="true“ class="org.example.ParentBean"> <property name="name" value="parent-AZ"/> <property name="age" value="31"/> </bean>

<bean id="childBean" class="org.example.ChildBean" parent="abstractBean" init-method="init">

<property name="name" value="child-AZ"/></bean>

Page 14: springframework-120522023855-phpapp02

Bean scopesBean scopes singleton(Default) Scopes a single bean definition to a single object instance per Spring IoC

container. prototype

Scopes a single bean definition to any number of object instances.

requestScopes a single bean definition to the lifecycle of a single HTTP request; that is, each

HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the

context of a web-aware SpringApplicationContext.

global sessionScopes a single bean definition to the lifecycle of a global HTTP Session. Typically only

valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

 custom scope To integrate your custom scope(s) into the Spring container, you need to implement

the org.springframework.beans.factory.config.Scope interface

Page 15: springframework-120522023855-phpapp02

The singleton scopeThe singleton scope The non-singleton, prototype scope of bean deployment results in the creation of a new bean

instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans.

The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.

<bean id="accountService" class=“DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class=“DefaultAccountService" scope="singleton“/>

Page 16: springframework-120522023855-phpapp02

The prototype scopeThe prototype scope The non-singleton, prototype scope of bean deployment results in the creation of a new bean

instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans.

The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.

<bean id="accountService" class=“DefaultAccountService" scope="prototype“/>

Page 17: springframework-120522023855-phpapp02

Request, session, and global Request, session, and global session scopessession scopes Request scope

The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the internal state of the instance that is created as much as you want, because other instances created from the same loginAction bean definition will not see these changes in state; they are particular to an individual request. When the request completes processing, the bean that is scoped to the request is discarded.

Session scope

The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.

Global session scope

The global session scope is similar to the standard HTTP Session scope and applies only in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session.

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session“/>

<bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession”/>

Page 18: springframework-120522023855-phpapp02

Lifecycle callbacksLifecycle callbacks Initialization callbacksInitialization callbacks Use the init-method attribute to specify the name of the method that has a void no-argument

signature.

To perform some initializing after the bean has been created.

Destruction callbacksDestruction callbacksUse the destroy-method attribute to specify the name of the method that has a void no-argument

signature. To perform some initializing after the bean has been created.

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init“/>public class ExampleBean { public void init() { // do some initialization work } }

<bean id="exampleInitBean" class=“ExampleBean" destroy-method="cleanup"

public class ExampleBean { public void init() { // do some initialization work } }

Page 19: springframework-120522023855-phpapp02

Spring AwareSpring AwareApplicationContextAwareApplicationContextAware

BeanNameAwareBeanNameAwarepublic class CommandManager implements BeanNameAware { private String name;

protected Command createCommand() { if(name .equals(“xyz”))}

public void setBeanName(string name) throws BeansException{ this.name-name; }}

public class CommandManager implements ApplicationContextAware { private ApplicationContext applicationContext;

protected Command createCommand() { return this.applicationContext.getBean("command", Command.class); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }

Page 20: springframework-120522023855-phpapp02

Container extension Container extension pointspointsCustomizing beans using the BeanPostProcessor InterfaceCustomizing beans using the BeanPostProcessor Interface

public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor { // simply return the instantiated bean as-is public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; // we could potentially return any object reference here... }

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("Bean '" + beanName + "' created : " + bean.toString()); return bean; }

<bean id="messenger“ class=“Messenger” <!-- when the above bean (messenger) is instantiated, this custom BeanPostProcessor implementation will output the fact to the system console --> <bean class=“InstantiationTracingBeanPostProcessor“/>

ApplicationContext ctx = new ClassPathXmlApplicationContext("scripting/beans.xml"); Messenger messenger = (Messenger) ctx.getBean("messenger");

Bean 'messenger' created : org.springframework.BeanFactory@272961

Page 21: springframework-120522023855-phpapp02

Container extension points (Cont’d)Container extension points (Cont’d) BeanFactoryPostProcessor BeanFactoryPostProcessor  The semantics of this interface are similar to the BeanPostProcessor, with one major

difference: BeanFactoryPostProcessors operate on the bean configuration metadata; that is, the Spring IoC container allows BeanFactoryPostProcessors to read the configuration metadata and potentially change it before the container instantiates any beans other than BeanFactoryPostProcessors..\

PropertyPlaceholderConfigurerPropertyPlaceholderConfigurer

  PropertyOverrideConfigurerPropertyOverrideConfigurer

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:com/foo/jdbc.properties"/> </bean>

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>

Properties file configuration lines take this format:beanName.property=value

For example:dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql:mydb

Page 22: springframework-120522023855-phpapp02

  Autowiring collaboratorsAutowiring collaborators The Spring container can autowire relationships between collaborating beans. You can allow

Spring to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext

When using XML-based configuration metadata[2], you specify autowire mode for a bean definition with the autowire attribute of the <bean/>element. The autowiring functionality has five modes. You specify autowiring per bean and thus can choose which ones to autowire.

Autowiring modes

Mode Explanation

no

(Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.

byName

Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..)method), Spring looks for a bean definition named master, and uses it to set the property.

byType

Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.

constructor

Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

Page 23: springframework-120522023855-phpapp02

Method injectionMethod injection In most application scenarios, most beans in the container are singletons. When a singleton bean

needs to collaborate with another singleton bean, or a non-singleton bean needs to collaborate with another non-singleton bean, you typically handle the dependency by defining one bean as a property of the other.

A problem arises when the bean lifecycles are different. Suppose singleton bean A needs to use non-singleton (prototype) bean B, perhaps on each method invocation on A. The container only creates the singleton bean A once, and thus only gets one opportunity to set the properties. The container cannot provide bean A with a new instance of bean B every time one is needed..

// a class that uses a stateful Command-style class to perform some processing public class CommandManager implements ApplicationContextAware { private ApplicationContext applicationContext;

public Object process(Map commandState) { // grab a new instance of the appropriate Command Command command = createCommand(); // set the state on the (hopefully brand new) Command instance command.setState(commandState); return command.execute(); }

protected Command createCommand() { // notice the Spring API dependency! return this.applicationContext.getBean("command", Command.class); }

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }

Page 24: springframework-120522023855-phpapp02

Lookup Method Lookup Method InjectionInjection

Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The lookup typically involves a prototype bean as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.

public class CommandManager {

public Object process(Map commandState) { // grab a new instance of the appropriate Command Command command = createCommand(); // set the state on the (hopefully brand new) Command instance command.setState(commandState); return command.execute(); }

// okay... but where is the implementation of this method?protected abstract Command createCommand() ;

<!-- a stateful bean deployed as a prototype (non-singleton) --> <bean id="command" class="AsyncCommand" scope="prototype“/>

<!-- commandProcessor uses statefulCommandHelper --> <bean id="commandManager" class="CommandManager"> <lookup-method name="createCommand" bean="command"/> </bean>

Page 25: springframework-120522023855-phpapp02

Bean FactoryBean Factory The BeanFactory is the actual container which instantiates, configures, and manages a

number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory (although some dependencies may not be visible as configuration data, but rather be a function of programmatic interactions between beans at runtime).

A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory, for which there are multiple implementations. The most commonly used simple BeanFactory implementation is org.springframework.beans.factory.xml.XmlBeanFactory.

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

ApplicationContextApplicationContext

Page 26: springframework-120522023855-phpapp02

Spring AOPSpring AOP

AOP Fundamentals Aspect-oriented programming (AOP) provides for simplified application of cross-

cutting concerns◦ Transaction management

◦ Security

◦ Logging

◦ Auditing

◦ Locking

Page 27: springframework-120522023855-phpapp02

AOP conceptsAOP concepts Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is

a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).

Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. (Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptorsaround the join point.

Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.

Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModifiedinterface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)

Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.

AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Page 28: springframework-120522023855-phpapp02

Spring AOP capabilities and Spring AOP capabilities and goalsgoals

Spring AOP currently supports only method execution join points. Aspects are configured using normal bean definition syntax Spring does not provide the most complete AOP

implementation ,it rather provides a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications.

Spring AOP will never strive to compete with AspectJ to provide a comprehensive AOP solution

Page 29: springframework-120522023855-phpapp02

Spring AdviceSpring Advice Before advice: Advice that executes before a join point, but which does not have the

ability to prevent execution flow proceeding to the join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

After throwing advice: Advice to be executed if a method exits by throwing an exception.

After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Page 30: springframework-120522023855-phpapp02

Spring PointcutsSpring PointcutsSpring AOP supports the following AspectJ pointcut designators (PCD) for use in

pointcut expressions: Execution - for matching method execution join points, this is the primary pointcut designator

you will use when working with Spring AOP

within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)

this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type

target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type

args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types

@target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type

@args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)

@within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)

@annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

Page 31: springframework-120522023855-phpapp02

DeclaringDeclaring Pointcut & AdvicePointcut & Advice Declaring A Pointcut

Declaring advice

<aop:config> <aop:advisor pointcut=“SystemArchitecture.businessService()" advice-ref="tx-advice"/> </aop:config>

<tx:advice id="tx-advice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>Or@Pointcut("execution(* com.xyz.someapp.service.*.*(..))") public void businessService() {}

@Aspect public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; }

Page 32: springframework-120522023855-phpapp02

TransactionsTransactions Comprehensive transaction support is among the most compelling

reasons to use the Spring Framework. The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).

Support for declarative transaction management. Simpler API for programmatic transaction management than

complex transaction APIs such as JTA. Excellent integration with Spring's data access abstractions.

Page 33: springframework-120522023855-phpapp02

Transaction ManagerTransaction Manager Spring does not directly manage transactions. Instead, it comes with a selection of transaction

managers that delegate responsibility for transaction management to a platform-specific transaction implementation provided by either JTA or the persistence mechanism

Transaction manager implementation

Purpose

org.springframework.jdbc.datasource.DataSourceTransactionManager

Manages transactions on a single JDBCDataSource

org.springframework.orm.hibernate.HibernateTransactionManager

Used to manage transactions when Hibernate is thepersistence mechanism.

org.springframework.orm.jdo.JdoTransactionManager

Used to manage transactions when JDO is used forpersistence.

org.springframework.transaction.jta.JtaTransactionManager

Manages transactions using a Java Transaction API(JTA ) implementation. Must be used when a transactionspans multiple resources.

org.springframework.orm.ojb.PersistenceBrokerTransactionManager

Manages transactions when Apache’s Object RelationalBridge (OJB) is used for persistence

Page 34: springframework-120522023855-phpapp02

Declarative Transaction Declarative Transaction ImplementationImplementation// the service interface that we want to make transactional public interface FooService {Foo getFoo(String fooName); Foo getFoo(String fooName, String barName);void insertFoo(Foo foo);}

<!-- this is the service object that we want to make transactional --> <bean id="fooService" class="x.y.service.DefaultFooService"/> <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) --> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- the transactional semantics... --> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*"/> </tx:attributes> </tx:advice>

<!-- ensure that the above transactional advice runs for any execution of an operation defined by the FooService interface --> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config>

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>

Page 35: springframework-120522023855-phpapp02

Declarative TransactionDeclarative Transaction

Page 36: springframework-120522023855-phpapp02

<tx:advice/> settings<tx:advice/> settings

Attribute Required? Default Description

name Yes  

Method name(s) with which the transaction attributes are to be associated. The wildcard (*) character can be used to associate the same transaction attribute settings with a number of methods; for example, get*, handle*, on*Event, and so forth.

propagation No REQUIRED Transaction propagation behavior.

isolation No DEFAULT Transaction isolation level.

timeout No -1 Transaction timeout value (in seconds).

read-only No false Is this transaction read-only?

rollback-for No  

Exception(s) that trigger rollback; comma-delimited. For example,com.foo.MyBusinessException,ServletException.

no-rollback-for

No  

Exception(s) that do not trigger rollback; comma-delimited. For example,com.foo.MyBusinessException,ServletException.

Page 37: springframework-120522023855-phpapp02

Spring’s Transactional Propagation Spring’s Transactional Propagation RulesRules

Propagation behavior What it means

PROPAGATION_NOT_SUPPORTED

Indicates that the method should not run within a transaction. If anexisting transaction is in progress, it will be suspended for theduration of the method. If using JTATransactionManager,access to TransactionManager is required.

PROPAGATION_REQUIRED

Indicates that the current method must run within a transaction. Ifan existing transaction is in progress, the method will run withinthat transaction. Otherwise, a new transaction will be started.

PROPAGATION_REQUIRES_NEW

Indicates that the current method must run within its own transaction.A new transaction is started and if an existing transaction is inprogress, it will be suspended for the duration of the method. Ifusing JTATransactionManager, access to Transaction-Manager is required.

PROPAGATION_SUPPORTS

Indicates that the current method does not require a transactionalcontext, but may run within a transaction if one is already inprogress.

Page 38: springframework-120522023855-phpapp02

Data AccessData Access

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way. This allows one to switch between the aforementioned persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

Page 39: springframework-120522023855-phpapp02

JDBC TemplateJDBC Template<bean id="corporateEventDao" class="com.example.JdbcCorporateEventDao"> <property name="dataSource" ref="dataSource"/> </bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>

<context:property-placeholder location="jdbc.properties"/>

@Repository public class JdbcCorporateEventDao implements CorporateEventDao { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); }

public List<Actor> findAllActors() { return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper()); }

private static final class ActorMapper implements RowMapper<Actor> { public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setLastName(rs.getString("last_name")); return actor; } }

Page 40: springframework-120522023855-phpapp02

Hibernate TemplateHibernate Template<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> </property> </bean>

<bean id="myProductDao" class="product.ProductDaoImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean>

public class ProductDaoImpl implements ProductDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; }

public Collection loadProductsByCategory(String category) { return this.sessionFactory.getCurrentSession() .createQuery("from test.Product product where product.category=?") .setParameter(0, category) .list(); } }

Page 41: springframework-120522023855-phpapp02

Hibernate TransactionHibernate Transaction<!-- SessionFactory, DataSource, etc. omitted --> <bean id="transactionManager“ class="org.springframework….HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean>

<aop:config> <aop:pointcut id="productServiceMethods" expression="execution(* product.ProductService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/></aop:config>

<tx:advice id="txAdvice" transaction-manager="myTxManager"> <tx:attributes> <tx:method name="increasePrice*" propagation="REQUIRED"/> <tx:method name="someOtherBusinessMethod" propagation="REQUIRES_NEW"/> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice>

<bean id="myProductService" class="product.SimpleProductService"> <property name="productDao" ref="myProductDao"/> </bean> public class ProductServiceImpl implements ProductService { private ProductDao productDao;

public void setProductDao(ProductDao productDao){ this.productDao = productDao; }

public void increasePriceOfAllProductsInCategory(final String category) { List productsToChange = this.productDao.loadProductsByCategory(category); /} }

Page 42: springframework-120522023855-phpapp02

Marshalling XML using O/X Marshalling XML using O/X MappersMappers

Spring's Object/XML Mapping support. Object/XML Mapping, or O/X mapping for short, is the act of converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization. Within the field of O/X mapping, a marshaller is responsible for serializing an object (graph) to XML. In similar fashion, an unmarshaller deserializes the XML to an object graph. This XML can take the form of a DOM document, an input or output stream, or a SAX handler.

Some of the benefits of using Spring for your O/X mapping needs are:

o Ease of configuration.

o Consistent Interfaces

o Consistent Exception Hierarchy

Marshaller and Unmarshaller

The Marshaller interface has one main method, which marshals the given object to a given javax.xml.transform.Result. Result is a tagging interface that basically represents an XML output abstraction: concrete implementations wrap various XML representations.

This interface also has one method, which reads from the given javax.xml.transform.Source (an XML input abstraction), and returns the object read. As with Result, Source is a tagging interface that has three concrete implementations. 

public interface Marshaller {void marshal(Object graph, Result result) throws XmlMappingException, IOException; }

public interface Unmarshaller {Object unmarshal(Source source) throws XmlMappingException, IOException; }

Page 43: springframework-120522023855-phpapp02

Using Marshaller and UnmarshallerUsing Marshaller and Unmarshaller

Page 44: springframework-120522023855-phpapp02

Spring RemotingSpring Remoting Spring features integration classes for remoting support using various technologies. The

remoting support eases the development of remote-enabled services, implemented by your usual (Spring) POJOs. Currently, Spring supports four remoting technologies:

Remote Method Invocation (RMI). Through the use of the RmiProxyFactoryBean and the RmiServiceExporter Spring supports both traditional RMI (with java.rmi.Remote interfaces and java.rmi.RemoteException) and transparent remoting via RMI invokers (with any Java interface).

Spring's HTTP invoker. Spring provides a special remoting strategy which allows for Java serialization via HTTP, supporting any Java interface (just like the RMI invoker). The corresponding support classes are HttpInvokerProxyFactoryBean and HttpInvokerServiceExporter.

Hessian. By using Spring's HessianProxyFactoryBean and the HessianServiceExporter you can transparently expose your services using the lightweight binary HTTP-based protocol provided by Caucho.

Burlap. Burlap is Caucho's XML-based alternative to Hessian. Spring provides support classes such as BurlapProxyFactoryBean and BurlapServiceExporter.

JAX-RPC. Spring provides remoting support for web services via JAX-RPC (J2EE 1.4's web service API).

JAX-WS. Spring provides remoting support for web services via JAX-WS (the successor of JAX-RPC, as introduced in Java EE 5 and Java 6).

JMS. Remoting using JMS as the underlying protocol is supported via the JmsInvokerServiceExporter and JmsInvokerProxyFactoryBean classes.

Page 45: springframework-120522023855-phpapp02

Remote Method Invocation (RMI).Remote Method Invocation (RMI). Using the RmiServiceExporter, we can expose the interface of our AccountService object as

RMI object. The interface can be accessed by using RmiProxyFactoryBean, or via plain RMI in case of a traditional RMI service. The RmiServiceExporter explicitly supports the exposing of any non-RMI services via RMI invokers.

Linking in the service at the client

<bean id="accountService" class="example.AccountServiceImpl“/>

<bean class="org.springframework.remoting.rmi.RmiServiceExporter"><!-- does not necessarily have to be the same name as the bean to be exported --><property name="serviceName" value="AccountService"/><property name="service" ref="accountService"/><property name="serviceInterface" value="example.AccountService"/><property name="registryPort" value="1199"/></bean>

<bean class="example.SimpleObject"><property name="accountService" ref="accountService"/></bean><bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"><property name="serviceUrl" value="rmi://HOST:1199/AccountService"/><property name="serviceInterface" value="example.AccountService"/></bean>

Page 46: springframework-120522023855-phpapp02