0% found this document useful (0 votes)
8 views

Aspect Oriented Programming With Spring

Aspect-Oriented Programming (AOP) enhances Object-Oriented Programming (OOP) by modularizing crosscutting concerns, with Spring providing a robust AOP framework that integrates seamlessly with its IoC container. Key AOP concepts include join points, advice, pointcuts, and aspects, which allow for declarative enterprise services and custom aspect implementations. Spring AOP supports method execution join points and utilizes proxies for advising objects, while also offering various configuration styles including AspectJ annotations.

Uploaded by

prashant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Aspect Oriented Programming With Spring

Aspect-Oriented Programming (AOP) enhances Object-Oriented Programming (OOP) by modularizing crosscutting concerns, with Spring providing a robust AOP framework that integrates seamlessly with its IoC container. Key AOP concepts include join points, advice, pointcuts, and aspects, which allow for declarative enterprise services and custom aspect implementations. Spring AOP supports method execution join points and utilizes proxies for advising objects, while also offering various configuration styles including AspectJ annotations.

Uploaded by

prashant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Aspect Oriented Programming with Spring

Introduction
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by
providing another way of thinking about program structure. The key unit of modularity in OOP
is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the
modularization of concerns such as transaction management that cut across multiple types and
objects. (Such concerns are often termed crosscutting concerns in AOP literature.)

One of the key components of Spring is the AOP framework. While the Spring IoC container
does not depend on AOP, meaning you do not need to use AOP if you don't want to, AOP
complements Spring IoC to provide a very capable middleware solution.

AOP is used in the Spring Framework to...

 ... provide declarative enterprise services, especially as a replacement for EJB declarative
services. The most important such service is declarative transaction management.
 ... allow users to implement custom aspects, complementing their use of OOP with AOP.

AOP concepts
AOP concepts and terminologies are as follows:
 Join point
 Advice
 Pointcut
 Introduction
 Target Object
 Aspect
 Interceptor
 AOP Proxy
 Weaving

Join point
Join point is any point in your program such as method execution, exception handling, field
access etc. Spring supports only method execution join point.

Advice
Advice represents an action taken by an aspect at a particular join point. There are different types
of advices:
Before Advice: it executes before a join point.
After Returning Advice: it executes after a joint point completes normally.
After Throwing Advice: it executes if method exits by throwing an exception.
After (finally) Advice: it executes after a join point regardless of join point exit whether
normally or exceptional return.
Around Advice: It executes before and after a join point.

Pointcut
It is an expression language of AOP that matches join points.

Introduction
It means introduction of additional method and fields for a type. It allows you to introduce new
interface to any advised object.

Target Object
It is the object i.e. being advised by one or more aspects. It is also known as proxied object in
spring because Spring AOP is implemented using runtime proxies.

Aspect
It is a class that contains advices, join points etc.

Interceptor
It is an aspect that contains only one advice.

AOP Proxy
It is used to implement aspect contracts, created by AOP framework. It will be a JDK dynamic
proxy or CGLIB proxy in spring framework.

Weaving
It is the process of linking aspect with other application types or objects to create an advised
object. Weaving can be done at compile time, load time or runtime. Spring AOP performs
weaving at runtime.
Spring AOP capabilities and goals
Spring AOP is implemented in pure Java. There is no need for a special compilation process.
Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a
Servlet container or application server.

Spring AOP currently supports only method execution join points (advising the execution of
methods on Spring beans). Field interception is not implemented, although support for field
interception could be added without breaking the core Spring AOP APIs. If you need to advise
field access and update join points, consider a language such as AspectJ.

Spring AOP's approach to AOP differs from that of most other AOP frameworks. The aim is not
to provide the most complete AOP implementation (although Spring AOP is quite capable); it is
rather to provide a close integration between AOP implementation and Spring IoC to help solve
common problems in enterprise applications.

Thus, for example, the Spring Framework's AOP functionality is normally used in conjunction
with the Spring IoC container. Aspects are configured using normal bean definition syntax
(although this allows powerful "autoproxying" capabilities): this is a crucial difference from
other AOP implementations. There are some things you cannot do easily or efficiently with
Spring AOP, such as advise very fine-grained objects (such as domain objects typically): AspectJ
is the best choice in such cases. However, our experience is that Spring AOP provides an
excellent solution to most problems in enterprise Java applications that are amenable to AOP.

Spring AOP will never strive to compete with AspectJ to provide a comprehensive AOP
solution.Both proxy-based frameworks like Spring AOP and full-blown frameworks such as
AspectJ are valuable, and that they are complementary, rather than in competition. Spring 2.0
seamlessly integrates Spring AOP and IoC with AspectJ, to enable all uses of AOP to be catered
for within a consistent Spring-based application architecture. This integration does not affect the
Spring AOP API or the AOP Alliance API: Spring AOP remains backward-compatible.

AOP Proxies

Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. This enables any
interface (or set of interfaces) to be proxied.

Spring AOP can also use CGLIB proxies. This is necessary to proxy classes, rather than
interfaces. CGLIB is used by default if a business object does not implement an interface. As it is
good practice to program to interfaces rather than classes, business classes normally will
implement one or more business interfaces. It is possible to force the use of CGLIB, in those
(hopefully rare) cases where you need to advise a method that is not declared on an interface, or
where you need to pass a proxied object to a method as a concrete type.
Hierarchy of advice interfaces

Following diagram shows the hierarchy of advice interface :

221

Ho

All are interfaces in aop.

 MethodBeforeAdvice interface extends the BeforeAdvice interface.

 AfterReturningAdvice interface extends the AfterAdvice interface.

 ThrowsAdvice interface extends the AfterAdvice interface.

 MethodInterceptor interface extends the Interceptor interface. It is used in around


advice.

Spring AOP
Spring AOP can be used by 3 ways given below. But the widely used approach is Spring AspectJ
Annotation Style. The 3 ways to use spring AOP are given below:

1. By Spring1.2 Old style (dtd based) (also supported in Spring3)


2. By AspectJ annotation-style
3. By Spring XML configuration-style(schema based)
@AspectJ support
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5
annotations. The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5
release. Spring 2.0 interprets the same annotations as AspectJ 5, using a library supplied by
AspectJ for pointcut parsing and matching. The AOP runtime is still pure Spring AOP though,
and there is no dependency on the AspectJ compiler or weaver.

Enabling @AspectJ Support

To use @AspectJ aspects in a Spring configuration you need to enable Spring support for
configuring Spring AOP based on @AspectJ aspects, and autoproxying beans based on whether
or not they are advised by those aspects. By autoproxying we mean that if Spring determines that
a bean is advised by one or more aspects, it will automatically generate a proxy for that bean to
intercept method invocations and ensure that advice is executed as needed.

The @AspectJ support is enabled by including the following element inside your spring
configuration:

<aop:aspectj-autoproxy/>

If you are using the DTD, it is still possible to enable @AspectJ support by adding the following
definition to your application context:

<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

You will also need two AspectJ libraries on the classpath of your
application: aspectjweaver.jar and aspectjrt.jar. These libraries are available in the 'lib' directory
of an AspectJ installation (version 1.5.1 or later required), or in the 'lib/aspectj' directory of the
Spring-with-dependencies distribution.

Declaring an aspect

With the @AspectJ support enabled, any bean defined in your application context with a class
that is an @AspectJ aspect (has the @Aspect annotation) will be automatically detected by
Spring and used to configure Spring AOP. The following example shows the minimal definition
required for a not-very-useful aspect:

A regular bean definition in the application context, pointing to a bean class that has
the @Aspect annotation:

<bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">


<!-- configure properties of aspect here as normal -->
</bean>

And the NotVeryUsefulAspect class definition, annotated


with org.aspectj.lang.annotation.Aspect annotation;

package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class NotVeryUsefulAspect {
}

Aspects (classes annotated with @Aspect) may have methods and fields just like any other class.
They may also contain pointcut, advice, and introduction (inter-type) declarations.

Declaring a pointcut

Spring AOP only supports method execution join points for Spring beans, so you can think of a
pointcut as matching the execution of methods on Spring beans. A pointcut declaration has two
parts: a signature comprising a name and any parameters, and a pointcut expression that
determines exactly which method executions we are interested in. In the @AspectJ annotation-
style of AOP, a pointcut signature is provided by a regular method definition, and the pointcut
expression is indicated using the @Pointcut annotation (the method serving as the pointcut
signature must have a void return type).

The following example defines a pointcut named 'anyOldTransfer' that will match the execution
of any method named 'transfer':

@Pointcut("execution(* transfer(..))")// the pointcut expression


private void anyOldTransfer() {}// the pointcut signature

The pointcut expression that forms the value of the @Pointcut annotation is a regular AspectJ 5
pointcut expression.

Supported Pointcut Designators


Spring 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

Spring AOP also supports an additional PCD named 'bean'. This PCD allows you to limit the
matching of join points to a particular named Spring bean, or to a set of named Spring beans
(when using wildcards). The 'bean' PCD has the following form:

bean(idOrNameOfBean)

Combining pointcut expressions


Pointcut expressions can be combined using '&&', '||' and '!'. It is also possible to refer to pointcut
expressions by name. The following example shows three pointcut
expressions: anyPublicOperation (which matches if a method execution join point represents the
execution of any public method); inTrading (which matches if a method execution is in the
trading module), and tradingOperation (which matches if a method execution represents any
public method in the trading module).

@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}
@Pointcut("within(com.xyz.someapp.trading..*)")
private void inTrading() {}

@Pointcut("anyPublicOperation() && inTrading()")


private void tradingOperation() {}

It is a best practice to build more complex pointcut expressions out of smaller named
components as shown above. When referring to pointcuts by name, normal Java visibility rules
apply (you can see private pointcuts in the same type, protected pointcuts in the hierarchy, public
pointcuts anywhere and so on). Visibility does not affect pointcut matching.

Sharing common pointcut definitions


While working with enterprise applications, you often want to refer to modules of the application
and particular sets of operations from within several aspects. For this purpose you can define a
"SystemArchitecture" aspect that captures common pointcut expressions. A typical such aspect
would look as follows:

package com.xyz.someapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class SystemArchitecture {

/**
* A join point is in the web layer if the method is defined
* in a type in the com.xyz.someapp.web package or any sub-package
* under that.
*/
@Pointcut("within(com.xyz.someapp.web..*)")
public void inWebLayer() {}
/**
* A join point is in the service layer if the method is defined
* in a type in the com.xyz.someapp.service package or any sub-package
* under that.
*/
@Pointcut("within(com.xyz.someapp.service..*)")
public void inServiceLayer() {}

/**
* A join point is in the data access layer if the method is defined
* in a type in the com.xyz.someapp.dao package or any sub-package
* under that.
*/
@Pointcut("within(com.xyz.someapp.dao..*)")
public void inDataAccessLayer() {}

/**
* A business service is the execution of any method defined on a service
* interface. This definition assumes that interfaces are placed in the
* "service" package, and that implementation types are in sub-packages.
*
* If you group service interfaces by functional area (for example,
* in packages com.xyz.someapp.abc.service and com.xyz.def.service) then
* the pointcut expression "execution(* com.xyz.someapp..service.*.*(..))"
* could be used instead.
*
* Alternatively, you can write the expression using the 'bean'
* PCD, like so "bean(*Service)". (This assumes that you have
* named your Spring service beans in a consistent fashion.)
*/
@Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
public void businessService() {}

/**
* A data access operation is the execution of any method defined on a
* dao interface. This definition assumes that interfaces are placed in the
* "dao" package, and that implementation types are in sub-packages.
*/
@Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
public void dataAccessOperation() {}

The pointcuts defined in such an aspect can be referred to anywhere that you need a pointcut
expression. For example, to make the service layer transactional, you could write:

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

<tx:advice id="tx-advice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
Examples
Spring AOP users are likely to use the execution pointcut designator the most often. The format
of an execution expression is:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-


pattern) throws-pattern?)

All parts except the returning type pattern (ret-type-pattern in the snippet above), name pattern,
and parameters pattern are optional. The returning type pattern determines what the return type
of the method must be in order for a join point to be matched. Most frequently you will use * as
the returning type pattern, which matches any return type. A fully-qualified type name will
match only when the method returns the given type. The name pattern matches the method name.
You can use the * wildcard as all or part of a name pattern. The parameters pattern is slightly
more complex: () matches a method that takes no parameters, whereas (..) matches any number
of parameters (zero or more). The pattern (*) matches a method taking one parameter of any
type, (*,String) matches a method taking two parameters, the first can be of any type, the second
must be a String.

Some examples of common pointcut expressions are given below.

 the execution of any public method:

execution(public * *(..))

 the execution of any method with a name beginning with "set":

execution(* set*(..))

 the execution of any method defined by the AccountService interface:

execution(* com.xyz.service.AccountService.*(..))

 the execution of any method defined in the service package:

execution(* com.xyz.service.*.*(..))

 the execution of any method defined in the service package or a sub-package:

execution(* com.xyz.service..*.*(..))
 any join point (method execution only in Spring AOP) within the service package:

within(com.xyz.service.*)

 any join point (method execution only in Spring AOP) within the service package or a
sub-package:

within(com.xyz.service..*)

 any join point (method execution only in Spring AOP) where the proxy implements
the AccountService interface:

this(com.xyz.service.AccountService)

 any join point (method execution only in Spring AOP) where the target object
implements the AccountService interface:

target(com.xyz.service.AccountService)

 any join point (method execution only in Spring AOP) which takes a single parameter,
and where the argument passed at runtime is Serializable:

args(java.io.Serializable)

Note that the pointcut given in this example is different to execution(*


*(java.io.Serializable)): the args version matches if the argument passed at runtime is
Serializable, the execution version matches if the method signature declares a single
parameter of type Serializable.

 any join point (method execution only in Spring AOP) where the target object has
an @Transactional annotation:

@target(org.springframework.transaction.annotation.Transactional)

'@target' can also be used in a binding form :- see the following section on advice for
how to make the annotation object available in the advice body.

 any join point (method execution only in Spring AOP) where the declared type of the
target object has an @Transactional annotation:
@within(org.springframework.transaction.annotation.Transactional)

'@within' can also be used in a binding form :- see the following section on advice for
how to make the annotation object available in the advice body.

 any join point (method execution only in Spring AOP) where the executing method has
an @Transactional annotation:

@annotation(org.springframework.transaction.annotation.Transactional)

'@annotation' can also be used in a binding form :- see the following section on advice
for how to make the annotation object available in the advice body.

 any join point (method execution only in Spring AOP) which takes a single parameter,
and where the runtime type of the argument passed has the @Classified annotation:

@args(com.xyz.security.Classified)

'@args' can also be used in a binding form :- see the following section on advice for how
to make the annotation object(s) available in the advice body.

 any join point (method execution only in Spring AOP) on a Spring bean named
'tradeService':

bean(tradeService)

 any join point (method execution only in Spring AOP) on Spring beans having names
that match the wildcard expression '*Service':

bean(*Service)

You might also like