2. The Spring Framework
Lightweight: Spring is lightweight in terms of both size (just
over 2..5 MB) and processing overhead.
Dependency Injection: Spring promotes loose coupling
through dependency injection (DI). When DI is applied, objects
are passively given their dependencies instead of creating or
looking for dependent objects for themselves.
Aspect-oriented: Spring comes with rich support for aspect-
oriented programming (AOP) that enables cohesive
development by separating application business logic from
system services.
Container: Spring is a container as it contains and manages the
lifecycle and configuration of application objects. One can
declare how each of your application objects should be
created, how they should be configured, and how they should be
associated with each other using Spring.
Framework: Spring allows to configure and compose complex
applications from simpler components and provides much
infrastructure functionality. In Spring, the application objects are
composed declaratively, typically in an XML file.
4. Spring Modules: Core and Context
Core Container: It provides the fundamental functionality
of the Spring Framework and contains the
BeanFactory, which is the fundamental Spring container.
Application context module: Spring’s application context
builds on the core container .
It extends the concept of BeanFactory, adding support for
internationalization (I18N) messages, application lifecycle
events, and validation.
In addition, it supplies many enterprise services such as
email, JNDI access, EJB integration, remoting, and
scheduling and support for integration with templating
frameworks such as Velocity and FreeMarker.
5. Spring Modules: AOP and DAO
Spring’s AOP module: It provides support for aspect-oriented
programming and basis for developing aspects in a Spring enabled
application. Like DI, AOP supports loose coupling of application
objects.
Spring’s AOP module offers several approaches to building
aspects, including building aspects based on AOP Alliance interfaces
and support for AspectJ.
JDBC abstraction and the DAO module: Spring’s JDBC and Data
Access Objects (DAO) module abstracts away the boilerplate code such
as getting a connection, creating a statement, processing a resultset to
keep the database code clean and simple, and prevents problems
resulting from failure to close database resources.
It also builds a layer of meaningful exceptions on top of the error
messages given by several database servers.
This module uses Spring’s AOP module to provide transaction
management services for objects in a Spring application.
6. Spring Modules: ORM
Object-relational mapping (ORM) integration
module: It provides ORM support over straight JDBC.
Spring’s ORM support builds on the DAO
support, providing a convenient way to build DAOs for
several ORM solutions.
Spring doesn’t attempt to implement its own ORM
solution, but does provide hooks into several popular ORM
frameworks, including Hibernate, Java Persistence
API, Java Data Objects, and iBATIS SQL Maps.
Spring’s transaction management supports each of these
ORM frameworks as well as JDBC.
7. Spring Modules: JMX, JCA, MVC
Java Management Extensions (JMX): Spring’s JMX module makes it
easy to expose the application’s beans as JMX Mbeans and makes it
possible to monitor and reconfigure a running application.
Java EE Connector API (JCA)
The Java EE Connection API (JCA) provides a standard way of
integrating Java applications with a variety of enterprise information
systems, including mainframes and databases.
JCA is much like JDBC, except where JDBC is focused on database
access, JCA is a more general-purpose API connecting to legacy
systems.
Spring’s support for JCA is similar to its JDBC support, abstracting away
JCA’s boilerplate code into templates.
The Spring MVC framework
Java has number of MVC frameworks, with Apache Struts, JSF,
WebWork, and Tapestry among the most popular MVC choices.
Spring integrates with several popular MVC frameworks and also has
its own capable MVC framework that promotes Spring’s loosely
coupled techniques in the web layer of an application.
8. Spring Modules: Portlet MVC, Web
Spring Portlet MVC: The portlet-based applications
aggregate several bits of functionality on a single web page.
It provides a view into several applications at once. Spring
Portlet MVC builds on Spring MVC to provide a set of
controllers that support Java’s portlet API.
Spring’s web module: Spring MVC and Spring Portlet
MVC require special consideration when loading the
Spring application context. Therefore, Spring’s web module
provides special support classes for Spring MVC and Spring
Portlet MVC.
The web module also supports several web-oriented tasks,
such as multipart file uploads and programmatic binding
of request parameters to your business objects.
It also contains integration support with Apache Struts and
JavaServer Faces.
9. Spring Modules: Remoting, JMS
Remoting
Spring’s remoting support enables the application to expose the
functionality of the Java objects as remote objects.
The remoting module also makes simple work of wiring remote
objects into the application as if they were local POJOs.
Several remoting options are available, including Remote
Method Invocation (RMI), Hessian, Burlap, JAX-RPC, and
Spring’s own HTTP Invoker.
Java Message Service (JMS)
Message-oriented communication, is reliable and guarantees
delivery of messages, even if the network and endpoints are
unreliable.
Spring’s Java Message Service (JMS) module helps to send
messages to JMS message queues and topics.
At the same time, this module also helps you create message-
driven POJOs that are capable of consuming asynchronous
messages.
10. Starting Spring
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="greetingService” class="com.spring.GreetingServiceImpl">
<property name="greeting" value="Buenos Dias!" />
</bean>
</beans>
At the root of the simple XML file is the <beans> element, which is the
root element of any Spring configuration file.
The <bean> element is used to tell the Spring container about a class
and how it should be configured.
The id attribute is used to name the bean greetingService and the class
attribute specifies the bean’s fully qualified class name.
Within the <bean> element, the <property> element is used to set a
property, in this case is the greeting property.
11. Starting Spring
The Spring can set the property through a single argument
constructor. For example:
<bean id="greetingService"
class="com.spring.chapter.hello.GreetingServiceImp">
<constructor-arg value="Buenos Dias!" />
</bean>
A BeanFactory loads the bean definitions and wires the beans
together.
The reference is obtained using getBean() method of BeanFactory
as shown in following code:
BeanFactory factory = new XmlBeanFactory(new
FileSystemResource("hello.xml"));
GreetingService greetingService =(GreetingService)
factory.getBean("greetingService");
12. Dependency Injection
Objects are given their dependencies at creation time
by some external entity that coordinates each object in
the system.
The key benefit of DI is loose coupling.
Loose Coupling: If an object only knows about its
dependencies by their interface (not their
implementation or how they were instantiated) then
the dependency can be swapped out with a different
implementation without the depending object
knowing the difference.
13. Aspect Oriented Programming
It is a programming technique that promotes separation of
concerns within a software system.
Some Systems have software components that carry
additional responsibility beyond their core functionality.
System services such as logging, transaction
management, and security often find their way into
components whose core responsibility is something else.
The code that implements the systemwide services is
duplicated across multiple components and the
components are littered with code that isn’t aligned with
their core functionality.
14. Aspect Oriented Programming
AOP makes it possible to modularize systemwide
services and then apply them declaratively to the
components that they should affect.
With AOP, one can cover the core application with
layers of functionality.
The layers can be applied declaratively throughout the
application in a flexible manner without allowing the
core application to know their existence.
This is a powerful concept, as it keeps the security,
transaction, and logging concerns from littering the
application’s core business logic.
16. Description of Aspect
■ First, find a <bean> declaration, or creates a bean in Spring. If the
bean doesn’t have any dependencies, then there’s no need to inject it
with anything.
■ Next, set up the <aop:config> element which contains most of
Spring’s AOP configuration elements.
■ Within <aop:config> we have an <aop:aspect> element which
indicates declaration of an aspect.
The functionality of the aspect is defined in the bean that is referred to
by the ref attribute.
An aspect is made up of pointcuts (places where the aspect
functionality will be applied) and advice (how to apply the
functionality).
■ The <aop:pointcut> element defines a pointcut that is triggered by
the execution of a method.
■ Finally, There are two bits of AOP advice. The <aop:before> element
declares a method to be called before the pointcut, while the
<aop:after> element declares the method to be called after the
pointcut.
The pointcut in both cases is a reference to id of
<aop:pointcut>, which is the execution of embarkOnQuest().
17. Spring Container
The spring container is at the core of the Spring Framework.
Spring’s container uses dependency injection (DI) to
manage the components that make up an application.
Spring comes with several container implementations that
can be categorized into two distinct types.
Bean factories (defined by the
org.springframework.beans.factory.BeanFactory interface)
are the simplest of containers, providing basic support for
DI.
Application contexts (defined by the
org.springframework.context.ApplicationContext interface)
build on the notion of a bean factory by providing
application framework services, such as the ability to
resolve textual messages from a properties file and the
ability to publish application events to interested event
listeners.
18. The BeanFactory
A bean factory is an implementation of the Factory design
pattern and is responsible for creating and dispensing
many types of beans.
It is able to create associations between collaborating
objects as they are instantiated and delivers fully
configured objects.
It also takes part in the lifecycle of a bean, making calls to
custom initialization and destruction methods, if those
methods are defined.
Most common implementation is XmlBeanFactory, which
loads its beans based on the definitions contained in an
XML file.
19. XMLBeanFactory
XmlBeanFactory requires to pass an instance of
org.springframework.core.io.Resource to the constructor.
The Resource object provides the XML to the factory.
FileSystemResource is commonly used to create an
XmlBeanFactory whose bean definitions are read from an
XML file in the file system:
BeanFactory factory = new XmlBeanFactory(new
FileSystemResource("c:/beans.xml"));
To retrieve a bean from a BeanFactory, simply call the
getBean() method, passing the ID of the bean to retrieve:
MyBean myBean = (MyBean)
factory.getBean("myBean");
When getBean() is called, the factory will instantiate the
bean and set the bean’s properties using DI thus beginning
the life of a bean within the Spring container.
20. Resource Implementations
Resource Implementn Purpose
ByteArrayResource Defines a resource whose content is given by an array of
bytes
ClassPathResource Defines a resource that is to be retrieved from the
classpath
DescriptiveResource Defines a resource that holds a resource description but
no actual readable resource
FileSystemResource Defines a resource that is to be retrieved from the file
system
InputStreamResource Defines a resource that is to be retrieved from an input
stream
PortletContextResource Defines a resource that is available in a portlet context
ServletContextResource Defines a resource that is available in a servlet context
UrlResource Defines a resource that is to be retrieved from a given
URL
21. Application Context
ApplicationContext is similar to BeanFactory as
ApplicationContext interface extends the BeanFactory interface.
It loads bean definitions, wire beans together, and dispense
beans upon request.
Application contexts provide a means for resolving text
messages, including support for internationalization (I18N) of
the messages.
Application contexts provide a generic way to load file
resources, such as images.
Application contexts can publish events to beans that are
registered as listeners.
An Application Context preloads all singleton beans upon
context startup compared to the bean factory which loads all
beans but defers bean creation until the getBean() method is
called.
22. Implementations of ApplicationContext
ClassPathXmlApplicationContext: Loads a context
definition from an XML file located in the classpath,
treating context definition files as classpath resources.
FileSystemXmlApplicationContext: Loads a context
definition from an XML file in the file system.
XmlWebApplicationContext: Loads context
definitions from an XML file contained within a web
application.
FileSystemXmlApplicationContext looks for the xml
file in a specific location within the file system,
whereas ClassPathXmlApplicationContext looks for
xml file anywhere in the classpath (including JAR
files).
24. Steps in Life of a Bean
Step Description
1. Instantiate Spring instantiates the bean.
2. Populate properties Spring injects the bean’s properties.
3. Set bean name. If the bean implements BeanNameAware, Spring passes
the bean’s ID to setBeanName().
4. Set bean factory. If the bean implements BeanFactoryAware, Spring
passes the bean factory to setBeanFactory().
5. Postprocess
(before init).
If there are any BeanPostProcessors, Spring calls their
postProcessBeforeInitialization() method.
6. Initialize beans. If the bean implements InitializingBean, its
afterPropertiesSet() method will be called.
7. Postprocess
(after init).
If there are any BeanPostProcessors, Spring calls their
postProcessAfterInitialization() method.
8. Bean is ready to use. Bean is ready to be used by the application and will
remain in the bean factory until it is no longer needed.
9. Destroy bean. If the bean implements DisposableBean, its destroy()
method will be called.
26. Declaring a Simple Bean
<bean id="duke" class="com.spring.springidol.Juggler" />
The <bean> element is the most basic configuration unit in
Spring.
It tells Spring to create an object for us.
The id attribute gives the bean a name by which it will be
referred to in the Spring container.
The class attribute tells Spring what type the bean will be.
When the Spring container loads its beans, it will
instantiate the bean defined using the default constructor.
ApplicationContext ctx = new
ClassPathXmlApplicationContext("spring-idol.xml");
Performer performer = (Performer) ctx.getBean("duke");
27. Injecting through constructors
<bean id="duke“ class="com.spring.springidol.Juggler">
<constructor-arg value="15" />
<constructor-arg ref="sonnet29" />
</bean>
The <constructor-arg> element is used to give Spring
additional information to use when constructing a bean
When a <constructor-arg> with a value attribute set, a
constructor taking the arguments other than the default
constructor is called.
The ref attribute is used to indicate that the value passed to
the constructor should be a reference to the bean.
Constructor injection is a surefire way to guarantee that a
bean is fully configured before it is used.
28. Injecting into bean properties
A JavaBean’s properties are private and will have a pair
of accessor methods in form of setXXX() and getXXX().
Bean properties can be configured using the
<property> element which injects the property by
calling a property’s setter method.
The value attribute of the <property> can be
Strings, numeric values as well as boolean values.
Similar to constructors, the ref attribute is used to
indicate that the value passed to the setter method
should be a reference to the bean.
29. Injecting inner beans
Inner beans are beans that are defined within the scope of
another bean.
<bean id="kenny” class="com.spring.Instrumentalist">
<property name="song" value="Jingle Bells" />
<property name="instrument">
<bean class="org.springinaction.springidol.Saxophone" />
</property>
</bean>
An inner bean is defined by declaring a <bean> element directly
as a child of the <property> element to which it will be injected.
Inner beans can be used to wire setter injection but also the
constructor arguments.
The inner beans do not have an id attribute set as one never
needs to refer to the inner bean by name.
Inner beans are only useful for injection once and can’t be
referred to by other beans.
30. Wiring Collections
Spring has four types of collection configuration elements.
The <list> and <set> elements are useful when configuring
properties that are either arrays or some implementation of
java.util.Collection.
The <map> and <props> are the two elements corresponding to
collections java.util.Map and java.util.Properties.
Collection
Element
Useful for
<list> Wiring a list of values, allowing duplicates.
<set> Wiring a set of values, ensuring no duplicates
<map> Wiring a collection of name-value pairs where name and
value can be of any type
<props> Wiring a collection of name-value pairs where the name
and value are both Strings
31. Lists, Arrays and Sets
The <list> element contains one or more values.
The <ref> elements are used to define the values as references to
other beans in the Spring context.
It is also possible to use other value-setting Spring elements as
the members of a <list>, including <value>, <bean>, and <null/>
A <list> may also contain another <list> as a member for
multidimensional lists.
<list> may be used with properties that are of any
implementation of java.util.Collection or an array.
<bean id="hank" class="com.spring.springidol.OneManBand">
<property name="instruments">
<list> <ref bean="guitar" /> <ref bean="cymbal" /> </list>
</property>
</bean>
<set> ensures that each of its members is unique.
32. Maps
The <map> element declares a value of type java.util.Map.
Each <entry> element defines a member of the Map.
The key attribute specifies the key of the entry as a String while
the key-ref attribute specifies the key of the entry as a reference
to another bean within the Spring context.
Similarly, the value attribute specifies the value of the entry as a
String while the value-ref attribute defines the value of the entry
as a reference to another bean within the Spring context.
<bean id="hank" class="com.spring.OneManBand">
<property name="instruments">
<map>
<entry key="GUITAR" value-ref="guitar" />
<entry key="CYMBAL" value-ref="cymbal" />
</map>
</property>
</bean>
33. Properties
Properties can be used instead of configuring a Map whose
entries have both String keys and String values.
The Properties class limits the keys and values to Strings.
The <props> element constructs a java.util.Properties value
where each member is defined by a <prop> element.
Each <prop> element has a key attribute that defines the key of
each Properties member, while the value is defined by the
contents of the <prop> element.
■ <props> is the element used to define a collection value of type
java.util.Properties.
■ <prop> is the element used to define a member value of a
<props> collection.
<property name="instruments">
<props>
<prop key="GUITAR">STRUM STRUM</prop>
</props>
</property>
34. Writing nulls
To set a property to null, you simply use the <null/>
element. For example:
<property name="someNonNullProperty">
<null/>
</property>
Another reason for explicitly wiring null into a
property is to override an autowired property value.
35. Autowiring
Spring automatically wires beans together by setting the autowire
property on each <bean> in order for Spring to autowire.
Spring provides four types of autowiring
■ byName—Attempts to find a bean in the container whose name (or
ID) is the same as the name of the property being wired. If a matching
bean is not found, the property will remain unwired.
■ byType—Attempts to find a single bean in the container whose type
matches the type of the property being wired. If no matching bean is
found, the property will not be wired. If more than one bean matches, an
org.springframework.beans.factory.UnsatisfiedDependencyException
will be thrown.
■ constructor—Tries to match up one or more beans in the container
with the parameters of one of the constructors of the bean being wired.
In the event of ambiguous beans or ambiguous constructors, an
org.springframework. beans.factory.UnsatisfiedDependencyException
will be thrown.
■ autodetect—Attempts to autowire by constructor first and then using
byType. Ambiguity is handled the same way as with constructor and
byType wiring.
36. Autowiring
By default, beans will not be autowired unless you set the
autowire attribute.
A default autowiring can be set for all beans within the
Spring context by setting default-autowire on the root
<beans> element. <beans default-autowire="byName">
Even after autowiring a bean, it can still use the <property>
element on any property as if autowire is not set.
In constructor autowiring, one cannot mix
<constructorarg> elements with constructor autowiring.
Autowiring lacks clarity as the Spring configuration XML
does not have the explicit details of wiring of the beans.
37. Bean Scoping
By default, all Spring beans are singletons.
To force Spring to produce a new bean instance each time
its needed, the bean’s scope attribute is set to prototype.
Spring Bean Scopes are as follows:
Scope Description
singleton Scopes the bean definition to a single instance per Spring container
(default).
prototype Allows a bean to be instantiated any number of times (once per use).
request Scopes a bean definition to an HTTP request. Only valid when used
with a webcapable Spring context (such as with Spring MVC).
session Scopes a bean definition to an HTTP session. Only valid when used
with a webcapable Spring context (such as with Spring MVC).
global-
session
Scopes a bean definition to a global HTTP session. Only valid when
used in a portlet context.
38. Creating Beans from Factory Methods
The <bean> element has a factory-method attribute to specify a static
method to be invoked instead of the constructor to create an instance of
a class.
Initialization on demand technique to configure singleton as bean in
spring:
public class Stage {
private Stage() {}
private static class SingletonHolder {
static Stage instance = new Stage();
}
public static Stage getInstance() {
return SingletonHolder.instance; }
}
To configure a bean in the Spring context, we simply use factory-
method as follows:
<bean id=“iStage“ class="co.Stage“ factory-method="getInstance" />
Factory methods can be used to wire an object produced by a static
method.
39. Initializing and destroying beans
The init-method attribute specifies a method that is to
be called on the bean immediately upon instantiation.
Similarly, destroy-method specifies a method that is
called just before bean is removed from the container.
<bean id="kenny"class="com.spring.Instrument"
init-method="tuneInstrument"
destroy-method="cleanInstrument">
</bean>
40. Defaulting methods and Bean Interfaces
If many of the beans in a context definition file will have
initialization or destroy methods with the same name, then
the default-init-method and default-destroy-method
attributes are used on the <beans> element.
The default-init-method / default-destroy-method
attribute sets an initialization / destroy method
respectively across all beans in a given context definition.
The class could also implement the two special Spring
interfaces: InitializingBean and DisposableBean, which
allows the bean to hook into the bean lifecycle.
The InitializingBean interface mandates that the class
implements afterPropertiesSet() and is called once all
specified properties for the bean have been set.
Similarly, DisposableBean requires that a destroy()
method be implemented. and is called when the bean is
disposed of by the container.
41. Aspect Oriented Programming (AOP)
In software development, functions that span multiple
points of an application are called cross-cutting
concerns.
Aspect-oriented programming helps to separate
cross-cutting concerns from business logic.
Cross-cutting concerns are modularized into special
objects called aspects.
Aspects are often described in terms of
advice, pointcuts, and joinpoints.
42. AOP Terminology
Advice: It is the job of an aspect.
Advice defines both the what and the when of an aspect.
Advice describes the job performed by aspect and
addresses the question of when to perform the job.
Jointpoints: A joinpoint is a point in the execution of the
application where an aspect can be plugged in.
Such point could be a method being called, an exception
being thrown, or even a field being modified.
These are the points where the aspect’s code can be
inserted into the normal flow of the application to add new
behavior.
43. AOP Terminology
Pointcut: Pointcuts help narrow down the joinpoints
advised by an aspect.
If advice defines the what and when of aspects then
pointcuts define the where.
A pointcut definition matches one or more joinpoints at
which advice should be woven.
Often you specify the pointcuts using explicit class and
method names or through regular expressions that define
matching class and method name patterns.
Aspect: An aspect is the merger of advice and pointcuts.
Advice and Pointcuts define everything there is to know
about an aspect—what it does and where and when it does
it.
44. AOP Terminology
Introduction: It allows to add new methods or attributes
to existing classes giving them new behavior and state.
Target: It is the object that is being advised. This can be
either an object written or a third-party object added for
custom behavior.
Without AOP, the object would have to contain its primary
logic plus the logic for any cross-cutting concerns.
With AOP, the target object is free to focus on its primary
concern, oblivious to any advice being applied.
Proxy: It is the object created after applying advice to the
target object. As far as the client objects are concerned, the
target object (pre-AOP) and the proxy object (post-AOP)
are the same—as they should be.
45. AOP Terminology
Weaving: It is the process of applying aspects to a target
object to create a new, proxied object.
The aspects are woven into the target object at the specified
joinpoints.
The weaving can take place at several points in the target
object’s lifetime:
■ Compile time—Aspects are woven in when the target
class is compiled.
■ Classload time—Aspects are woven in when the target
class is loaded into the JVM.
■ Runtime—Aspects are woven in sometime during the
execution of the application. Typically, an AOP container
will dynamically generate a proxy object that will delegate
to the target object while weaving in the aspects. Same as
Spring AOP.
46. Spring AOP
The ability to create pointcuts that define the joinpoints at
which aspects should be woven makes it an AOP framework.
Spring’s support for AOP comes in four flavors:
■ Classic Spring proxy-based AOP (available in all versions
of Spring)
■ @AspectJ annotation-driven aspects (only available in
Spring 2.0)
■ Pure-POJO aspects (only available in Spring 2.0)
■ Injected AspectJ aspects (available in all versions of
Spring)
The first three items are all variations on Spring’s proxy-
based AOP.
47. Spring Advises Objects at Runtime
In Spring, aspects are woven into Spring-managed
beans at runtime by wrapping them with a proxy class.
The proxy class poses as the target bean, intercepting
advised method calls and forwarding those calls to the
target bean.
Between the time that the proxy intercepts the method
call and the time it invokes the target bean’s
method, the proxy performs the aspect logic.
In case of an ApplicationContext, the proxied objects
will be created when it loads all of the beans from the
BeanFactory.
48. Spring Advises Objects at Runtime
Spring generates proxied classes in two ways.
If the target object implements an interface(s) that exposes
the required methods, Spring uses the
java.lang.reflect.Proxy class which allows to dynamically
generate a new class that implements the necessary
interfaces, weave in any advice, and proxy any calls to the
interfaces to the target class.
If your target class does not implement an interface, Spring
uses the CGLIB library to generate a subclass to your target
class.
When creating this subclass, Spring weaves in advice and
delegates calls to the subclass to the target class.
■ Creating a proxy with interfaces is favored over proxying
classes, since this leads to a more loosely coupled
application.
■ Methods marked as final cannot be advised.
Spring only supports method joinpoints.
49. Creating classic Spring Aspects
All of the interfaces are part of the Spring
Framework, except for MethodInterceptor.
The five types of advice, defined by an interface are as
follows:
Advice type Interface
Before org.springframework.aop.MethodBeforeAdvice
After-returning org.springframework.aop.AfterReturningAdvice
After-throwing org.springframework.aop.ThrowsAdvice
Around org.aopalliance.intercept.MethodInterceptor
Introduction org.springframework.aop.IntroductionInterceptor
50. Before Advice and After Advice
MethodBeforeAdvice interface requires a before() method to be
implemented:
public void before(Method method, Object[] args, Object target) { }
The before() method takes three parameters.
The first parameter is a java.lang.reflect.Method object that represents
the method to which the advice is being applied.
The second parameter is an array of Objects that are the arguments that
were passed to the method when the method was called.
The final parameter is the target of the method invocation (i.e., the
object on which the method was called).
AfterReturningAdvice requires that an afterReturning() method to be
implemented:
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) { }
The only difference from the before method is that an additional
parameter has been added as the first parameter which holds the value
that was returned from the invoked method.
AfterReturningAdvice only allows you to inspect the returned value, not
to change it.
51. After throwing advice
ThrowsAdvice interface doesn’t require that any
method be implemented.
ThrowsAdvice is only a marker interface that tells
Spring that the advice may wish to handle a thrown
exception.
An implementation of ThrowsAdvice may implement
one or more afterThrowing() methods whose
signatures take the following form:
public void afterThrowing([method], [args], [target],
throwable);
52. Around advice
Around advice is effectively before, after-returning, and
after-throwing advice all rolled into one.
In Spring, around advice is defined by the AOP Alliance’s
MethodInterceptor interface.
The MethodInterceptor interface requires that only an
invoke() method be implemented.
It calls proceed() on the method invocation to cause the
advised method to be invoked.
Around advice makes it possible to write advice that
performs some postprocessing on a method’s return value
before returning the value to the caller.
53. Defining pointcuts and advisors
The joinpoints are the points within application code
where aspect advice could be woven in.
Pointcuts are a way of selecting a subset of all possible
joinpoints where advice should be woven.
Two of the most useful pointcuts are regular
expression pointcuts and AspectJ expression pointcuts.
54. Regular Expression Pointcut
Pointcut selects the method(s) that advice will be applied
to, usually by matching a method signature against some
pattern.
Spring comes with two classes that implement regular
expression pointcuts:
■org.springframework.aop.support.Perl5RegexpMethodP
ointcut—Useful when an application will be running in a
pre-Java 1.4 environment. Requires Jakarta ORO.
■org.springframework.aop.support.JdkRegexpMethodPo
intcut—Best choice when running in Java 1.4 or higher.
Does not require Jakarta ORO.
Jakarta ORO: A set of text-processing Java classes that
provide Perl5 compatible regular expressions.
55. Declaring regular expression pointcut
<bean id="performPointcut“
class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*perform" />
</bean>
The pattern property is used to specify the pointcut pattern used in
method matching.
The pattern property has been set to a regular expression that
should match any method in any class.
The regular expression pointcut is associated with an advice using
the <bean> element.
DefaultPointcutAdvisor is an advisor class that simply associates
advice with a pointcut.
<bean id="audienceAdvisor"
class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="audienceAdvice" />
<property name="pointcut" ref="performancePointcut" />
</bean>
56. Combining a pointcut with advisor
RegexpMethodPointcutAdvisor is a special advisor
class that lets you define both a pointcut and an
advisor in a single bean.
The <bean> declaration is as follows:
<bean id="audienceAdvisor"
class="org.springframework.aop.support.
➥ RegexpMethodPointcutAdvisor">
<property name="advice" ref="audienceAdvice" />
<property name="pattern" value=".*perform" />
</bean>
57. Defining AspectJ pointcuts
AspectJ’s pointcut language is a true pointcut expression language.
AspectJ-style expressions can be used to defining the Spring
pointcuts, using AspectJExpressionPointcut.
The following <bean> declares the performance pointcut using an
AspectJ pointcut expression:
<bean id="performancePointcut"
class="org.springframework.aop.aspectj.
➥ AspectJExpressionPointcut">
<property name="expression" value="execution(*
Performer+.perform(..))" />
</bean>
The pointcut expression is defined as a value of the expression
property.
58. Defining AspectJ pointcuts
The AspectJ expression pointcut can be associated with the advice using
the DefaultPointcutAdvisor, similar to the regular expression
pointcut.
Also, a special advisor allows to define the pointcut expression as a
property of the advisor simplifying how pointcuts and advice are tied
together.
For AspectJ pointcut expressions, the advisor class to use is
AspectJExpressionPointcutAdvisor.
The following <bean> applies the advice to a method using an AspectJ
pointcut expression:
<bean id="audienceAdvisor"
class="org.springframework.aop.aspectj.
➥ AspectJExpressionPointcutAdvisor">
<property name="advice" ref="audienceAdvice" />
<property name="expression" value="execution(* *.perform(..))" />
</bean>
59. AspectJ-style pointcuts
Spring AOP uses Aspect-style pointcuts to select places to apply
advice.
Following is the pointcut which specifies the advice that should
be applied on any method named “perform” on any class with
any number of arguments.
60. ProxyFactoryBean
A proxied bean allows to be advised by an advisor.
Spring’s ProxyFactoryBean is a factory bean that produces a proxy
that applies one or more interceptors (and advisors) to a bean.
The following <bean> definition creates a proxy for the duke bean:
<bean id="duke”
class="org.springframework.aop.framework.ProxyFactoryBe
an">
<property name="target" ref="dukeTarget" />
<property name="interceptorNames"
value="audienceAdvisor" />
<property name="proxyInterfaces“ value="com.Performer" />
</bean>
The proxy will use the pointcut to decide whether advice should be
applied (or not), and then it invokes the advised bean itself.
61. ProxyFactoryBean
The target property tells ProxyFactoryBean which bean it will
be proxying.
The interceptorNames property tells ProxyFactoryBean which
advisors to apply to the proxied bean.
The interceptorNames property takes an array of Strings, of
which each member is the name of an interceptor/advisor bean
in the Spring context. An array is represented by XML as follows:
<property name="interceptorNames">
<list> <value>audienceAdvisor</value> </list>
</property>
The final property set on ProxyFactoryBean is proxyInterfaces
which tells ProxyFactoryBean which interface(s) the proxy
should implement.
ProxyFactoryBean produces a Java dynamic proxy that advises
the target bean and the proxyInterfaces provides a way to invoke
methods on that proxy.
The proxyInterfaces property is actually, an array of
java.lang.Class.
62. Abstracting ProxyFactoryBean
When the proxyInterfaces property and the interceptorNames property are the
same for all the beans, but only the target property is different then an abstract
ProxyFactoryBean is used.
When a single ProxyFactoryBean is declared as an abstract bean, then that
declaration is reused as a parent for each of the advised beans.
<bean id="audienceProxyBase"
class="org.springframework.aop.framework.ProxyFactoryBean“ abstract="true">
<property name="proxyInterfaces“ value="com.spring.Performer" />
<property name="interceptorNames" value="audienceAdvisor" />
</bean>
The abstract attribute set to true indicates that it is an abstract bean and that
Spring shouldn’t try to instantiate it directly.
Instead, the bean will serve as the basis for the other performer beans.
<bean id="stevie" parent="audienceProxyBase">
<property name="target" ref="stevieTarget" />
</bean>
Only variant target property is declared while common properties are inherited
from the parent bean.
63. Autoproxying
Spring provides support for automatic proxying of beans.
Autoproxying provides a more complete AOP
implementation by letting an aspect’s pointcut definition
decide which beans need to be proxied, rather than
explicitly create proxies for specific beans.
Two ways to autoproxy beans:
■ Basic autoproxying of beans based on advisor beans
declared in the Spring context—The advisor’s pointcut
expression is used to determine which beans and which
methods will be proxied.
■ Autoproxying based on @AspectJ annotation-driven
aspects—The pointcut specified on the advice contained
within the aspect will be used to choose which beans and
methods will be proxied.
64. Basic Autoproxying
Spring comes with a handy implementation of BeanPostProcessor
called DefaultAdvisorAutoProxyCreator, which automatically
checks to see whether an advisor’s pointcut matches a bean’s
methods and replaces that bean’s definition with a proxy
automatically that applies the advice.
The DefaultAdvisorAutoProxyCreator is used with the following
<bean> in the Spring context:
<bean
class="org.springframework.aop.framework.autoproxy.
➥ DefaultAdvisorAutoProxyCreator" />
The bean doesn’t have an id as it is never referred directly.
The Spring container recognizes it as a BeanPostProcessor and
puts it to work creating proxies.
When the DefaultAdvisorAutoProxyCreator is declared, its no
longer required to declare ProxyFactoryBeans in the Spring
context give the beans weird names that end with target.
65. Autoproxying @AspectJ aspects
AspectJ 5 is the ability to annotate POJO classes to be aspects
sprinkling a few annotations around.
The @Pointcut annotation is used to define a reusable pointcut within
an @AspectJ aspect.
The name of the pointcut is derived from the name of the method to
which the annotation is applied.
The value given to the @Pointcut annotation is an AspectJ pointcut
expression.
@Pointcut("execution(* *.perform(..))")
public void performance() {}
Each of the audience’s methods has been annotated with advice
annotations.
The @Before annotation applied to the methods to indicate that the
methods are before advice.
The @AfterReturning annotation indicates that the method is an
afterreturning advice method.
The @AfterThrowing annotation placed on a method in order to be
called if any exceptions are thrown during the performance.
The name of the method pointcut is given as the value parameter to all
of the advice annotations which tells each advice method where it
should be applied. For example: @Before("performance()")
66. Autoproxying @AspectJ aspects
An autoproxy bean in the Spring context which knows to turn
@AspectJ-annotated beans into proxy advice must be declared.
Spring comes with an autoproxy creator class called
AnnotationAwareAspectJAutoProxyCreator and also provides a
custom configuration element in the aop namespace making it easier
to register the autoproxy creator class in the Spring context.
<aop:aspectj-autoproxy />
It creates an AnnotationAwareAspectJAutoProxyCreator in the Spring
context and automatically proxy beans whose methods match the
pointcuts defined with @Pointcut annotations in @Aspectannotated
beans.
The <aop:aspectj-autoproxy> element is used by including the aop
namespace in the Spring configuration file.
AnnotationAwareAspectJAutoProxyCreator also creates proxies based
on classic Spring advisors.
The @around annotation before the method isn’t enough to provide a
proceed() method to call. Therefore, methods that are to be around
advice must take a ProceedingJoinPoint object as an argument and
then call the proceed() method on that object.
67. Spring 2.0’s AOP configuration elements
Spring’s AOP configuration elements can be used to turn any
class into an aspect without the source code of the class.
AOP configuration
element
Purpose
<aop:advisor> Defines an AOP advisor.
<aop:after> Defines an AOP after advice (regardless of whether the
advised method returns successfully).
<aop:after-returning> Defines an AOP after-returning advice.
<aop:after-throwing> Defines an AOP after-throwing advice.
<aop:around> Defines an AOP around advice.
<aop:aspect> Defines an aspect.
<aop:before> Defines an AOP before advice.
<aop:config> The top-level AOP element. Most <aop:*> elements must
be contained within <aop:config>.
<aop:pointcut> Defines a pointcut.
69. Injecting AspectJ aspects
AspectJ offers many types of pointcuts that are not possible
with Spring AOP.
AspectJ aspects are independent of Spring.
If an aspect depends on one or more classes when executing
its advice, one can instantiate those collaborating objects
with the aspect itself or using Spring’s dependency injection
to inject beans into AspectJ aspects.
To use Spring’s dependency injection to inject collaborators
into an AspectJ aspect, the aspect is declared as a <bean> in
Spring’s configuration.
<bean class="com.springinaction.springidol.JudgeAspect"
factory-method="aspectOf">
<property name="criticismEngine" ref="criticismEngine" />
</bean>
71. Injecting AspectJ aspects
Spring beans are instantiated by the Spring
container—but AspectJ aspects are created by the
AspectJ runtime.
All AspectJ aspects provide a static aspectOf()
method that returns the singleton instance of the
aspect to get an instance of the aspect, using the
factory-method to invoke the aspectOf() method.
Spring retrieves a reference to the aspect through the
aspectOf() factory method and then performs
dependency injection on it as prescribed by the
<bean> element.