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

Creating Aspects: Introducing AOP

The document provides an overview of key concepts in aspect-oriented programming (AOP) including aspects, joinpoints, advice, pointcuts, introductions, proxies, weaving, and how these concepts are implemented in the Spring framework. It defines common AOP terminology, describes the different types of advice in Spring like before, after returning, around advice, and throws advice. It also explains how to define pointcuts and advisors in Spring.

Uploaded by

rakeshrf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Creating Aspects: Introducing AOP

The document provides an overview of key concepts in aspect-oriented programming (AOP) including aspects, joinpoints, advice, pointcuts, introductions, proxies, weaving, and how these concepts are implemented in the Spring framework. It defines common AOP terminology, describes the different types of advice in Spring like before, after returning, around advice, and throws advice. It also explains how to define pointcuts and advisors in Spring.

Uploaded by

rakeshrf
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Creating aspects

Introducing AOP

Most definitions of AOP say something about the modularization of crosscutting concerns.

This figure represents a typical application that is broken down into modules.Each module’s main concern is to
provide services for its particular domain.However, each of these modules also requires similar ancillary
functionalities, such as security and transaction management. The common object-oriented technique for
reusing common functionality is through inheritance or delegation.

Defining AOP terminology

Aspect
An aspect is the cross-cutting functionality you are implementing. It is the aspect, or area, of your
application you are modularizing. The most common (albeit simple) example of an aspect is logging.

Joinpoint
A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point
could be a method being called, an exception being thrown, or even a field being modified.

Advice
Advice is the actual implementation of our aspect. It is advising your application of new behavior.

Pointcut
A pointcut defines at what joinpoints advice should be applied. Advice can be applied at any joinpoint
supported by the AOP framework.

Introduction
An introduction allows you to add new methods or attributes to existing classes.

Target
A target is the class that is being advised. This can be either a class you write or a third-party class to
which you want to add custom behavior.
Proxy
A proxy is the object created after applying advice to the target object.
Weaving
Weaving 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 class’s lifetime:
■ Compile time—Aspects are woven in when the target class is compiled. This requires a special

compiler.
■ Classload time—Aspects are woven in when the target class is loaded into the JVM. This requires a

special ClassLoader that enhances that target class’s bytecode before the class is introduced into the application.
■ Runtime—Aspects are woven in sometime during the execution of the application. Typically, an AOP

container will dynamically generate a proxy class that will delegate to the target class while weaving in the
aspects

Figure: Key AOP concepts in action.

Spring’s AOP implementation


All of the advice you create within Spring will be written in a standard Java class. The pointcuts that
define where advice should be applied are typically written in XML in your Spring configuration file.

Spring’s advises objects at runtime


Spring does not create a proxied object until that proxied bean is needed by the application. If you are
using an ApplicationContext, the proxied objects will be created when it loads all of the beans from the
BeanFactory.

Spring generates proxied classes in two ways.


1. If your target object implements an interface(s) that exposes the required methods, Spring will use the
JDK’s java.lang.reflect.Proxy class. This class allows Spring to dynamically generate a new class that
implements the necessary interfaces, weave in any advice, and proxy any calls to these interfaces to
your target class.
2. If your target class does not implement an interface, Spring uses the CGLIB library to generate a
subclass to your target class.
When using 2nd type of proxy generation, you need to deploy all of the JAR files in the lib/cglib directory
of your Spring distribution with your application. There are two important things to take note of when using
this approach:
■ 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 generates a subclass to your target class. Any method

that needs to be advised is overridden and advice is woven in. This is not possible with final methods.
Spring implements AOP Alliance interfaces

Spring only supports method joinpoints

Creating advice
Table Advice types in Spring

\
These different advice types give you opportunities to add behavior before and after a method
invocation, as well as when a method throws an exception.

Before advice
MethodBeforeAdvice interface provides you with access to the target method, the arguments passed to
this method, and the target object of the method invocation.
public interface MethodBeforeAdvice {
void before(Method method, Object[] args, Object target)throws Throwable
}
In the example above, we tell Spring to create a bean that does the following:
■ Implements the KwikEMart interface

■ Applies the WelcomeAdvice (id welcomeAdvice) advice object to all incoming calls

■ Uses the ApuKwikEMart bean (id kwikEMartTarget) as the target object

After advice
In this we implement AfterReturningAdvice interface:
public interface AfterReturningAdvice {
void afterReturning(Object returnValue, Method method,Object[] args, Object target) throws Throwable
}
}

Like MethodBeforeAdvice, this advice gives you access to the method that was called, the arguments
that were passed, and the target object.

Around advice
So far we have seen how to weave advice before and after a method. MethodInterceptor provides the
ability to do both in one advice object:
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}

There are two important differences between the MethodInterceptor interface and the previous two types of
advice:
1. The MethodInterceptor implementation controls whether the target method is actually invoked.
Invoking the target method is done by calling MethodInvocation.proceed().
2. MethodInterceptor gives you control over what object is returned. This means you can return a
completely different object than the one returned by proceed().

MethodInterceptor in an AOP Alliance interface. Any advice you implement using this interface is
compatible with any other AOP framework that is compliant with the AOP Alliance.

Throws advice
ThrowsAdvice lets you define behavior should an exception occur. Unlike the previous advice types,
ThrowsAdvice is a marker interface and contains no methods that need to be implemented. Instead, a class that
implements this interface must have at least one method with either of the following two signatures:
void afterThrowing(Throwable throwable)
void afterThrowing(Method method, Object[] args, Object target, Throwable throwable)

Introduction advice
Introduction advice adds new methods (and attributes) to the target object.
Defining pointcuts

Pointcuts determine if a particular method on a particular class matches a particular criterion. If the
method is indeed a match, then advice will be applied to this method.

Defining a pointcut in Spring


Spring defines pointcuts in terms of the class and method that is being advised.

The core interface for Spring’s pointcut framework is, the Pointcut interface.
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
}

The ClassFilter interface determines if a class is eligible for advising:


public interface ClassFilter {
boolean matches(Class clazz);
}
ClassFilter lets you filter your aspects by class, you are more likely interested in filtering by method. This
feature is provided by the MethodMatcher interface:
public interface MethodMatcher {
boolean matches(Method m, Class targetClass);
public boolean isRuntime();
public boolean matches(Method m, Class target, Object[] args);
}
The matches(Method, Class) method determines whether a method is a candidate to be advised based on
the target Class and Method.
If matches(Method, Class) returns true, isRuntime() is called to determine what type of MethodMatcher this
is. There are two types: static and dynamic:
 Static pointcuts define advice that is always executed. If a pointcut is static,
isRuntime()should return false.
 Dynamic pointcuts determine if advice should be executed by examining the
runtime method arguments. If a pointcut is dynamic, isRuntime()should return true.
Like matches(Method, Class), isRuntime() is only called once—when the proxy class is created.

If a pointcut is static, matches(Method, Class, Object[]) is never called, since runtime arguments are not
necessary for determining whether advice should be applied. For dynamic pointcuts, the matches(Method, Class,
Object[]) method is called at runtime for every invocation of the target method.
Use static pointcuts wherever possible to reduce the runtime overhead.

Understanding advisors
Most aspects are a combination of advice that defines the aspect’s behavior and a pointcut defining
where the aspect should be executed. Spring recognizes this and offers advisors, which combine advice and
pointcuts into one object. More specifically, the PointcutAdvisor does this.
public interface PointcutAdvisor {
Pointcut getPointcut();
Advice getAdvice();
}

Using Spring’s static pointcuts


Spring provides a convenience superclass for creating static pointcuts: StaticMethodMatcherPointcut. So
if you want to create a custom static pointcut, you can override this class and implement the isMatch method.
But for most of your needs, you will use a static pointcut provided by Spring.
NameMatchMethodPointcut
NameMatchMethodPointcut class has two methods you should be interested in:
public void setMappedName(String)
public void setMappedNames(String[])
You can provide explicit method names or use the wildcard character * at the beginning or end of the name.

instead of supplying the wildcard characters, we just as easily explicitly name each of these methods:
<property name="mappedNames">
<list>
<value>orderFurniturePolishing</name>
<value>orderWindowCleaning</name>
</list>
</property>
Regular expression pointcuts
Spring’s RegexpMethodPointcut lets you leverage the power of regular expressions to define your
pointcuts.

You might also like