Spring Aspect Oriented Programming in Java

By Johnny Morgan, December 29, 2016
Aspect Oriented Programming is a different style of writing code in modular way by allowing separation of cross cutting concerns. Implementing in modular way increases the better understanding, testability and also we can easily extend the behavior. AOP will add additional behavior to our code without modifying any code. Instead of modifying the code it adds behavior by using Advice and point cut. Common examples where aspects are used in logging, security, auditing, caching, transactions etc. AOP will intercept all method executions, variable declarations etc. in an applications, it will extend the behavior before and after the executions and declarations, but spring AOP only supports for method executions, AspectJ is one of the framework which does both. If we are using only method executions then Spring AOP is preferable than AspectJ. Before we understand the AOP concepts we need to familiar with AOP Terminologies.

AOP Terminologies

1) Aspect: An aspect is a class that contains concerns that cut across the application, like Transaction Management, it may cut across different classes in an application. The Aspects may be configured using xml schema approach or using @Aspect annotation.
2) Join Point: This represents the point in our application where we can plug-in our aspect, and also this is the point where action will take place in an application using advices. In Spring AOP, a join point always represents a method execution.
3) Advice: It is the action taken by an aspect at that joint point, this is the actual piece of code executed by Spring AOP framework. The advices may be invoke before execution of method, after execution of method, etc. In an Aspect frameworks the advice is behave similar to interceptor, a joint point may contain chain of advices around it.
4) PointCut: it is an expression/patterns that matches the joint point, an advice associated with that runs at any joint point. The concept of join points as matched by pointcut expressions is central to AOP. Spring AOP uses AspectJ expression language by default.
5) Introduction: Declaring additional fields, methods on advised object. Spring AOP allows us to implement interface to any advised object to provide additional behavior to it.

Example: we can implement the isModified interface for advised object to provide caching behavior.

6) Target Object: The object being advised by one or more no of aspects also called as advised object. As spring AOP implements runtime proxies so the target object will be a proxy always.
7) AOP Proxy: The wrapper object created by Spring AOP in order to implement advises methods. The Spring AOP proxy may be a JDK dynamic Proxy or CGLIB Proxy depending on configuration specified to spring AOP.
8) Weaving: It is the process to link aspects with other types of application types. This can be done at either at compile, load time or run time. Spring AOP performs waving at run time using proxies.

Types of Advices

1) Before Advice: The advice that executes before a joint point, but it will not stop the execution flow, unless it will throw the exception.
2) After returning Advice: This advice executes after successful execution of method.
3) After throwing Advice: This advice executes after a method exists by throwing exception.
4) After advice: Advice to be executed regardless of join point exists either successful or after throwing exception.
5) Around Advice: advice that surrounds a method invocation, this is the most powerful advice which will be called before the invocation and also after the invocation. And also using advice we can also choose either to proceed to execute joint point or advised the method can return its own value or throwing an exception.

AOP Proxies

Spring AOP is creates proxies in two ways.
1) JDK dynamic Proxies: It is the default proxy creation if a class implements an interface.
2) CGLIB Proxies: It is the default proxy creation if a class don't implement any interface. We can also force Spring AOP to create CGLIB Proxy even if a class implements an interface.

Creating Aspects

@AspectJ Annotation: This annotation is used to tell Spring AOP it is an aspect class, for understanding this annotation we need to enable AspectJ support. We can enable this support in two ways either using XML configuration or Java Annotation style.
Before enabling support we need to make sure that aspectjweaver.jar is present in class path.

Enabling @AspectJ annotation support using Java Configuration

To enable java configuration we need to add @EnableAspectJAutoProxy annotation on one of @Configuration annotated class, it has two attributes proxyTargetClass and exposeProxy.

proxyTargetClass attribute is accept the Boolean value either we use CGLIB proxies for interface implemented class, default value is false, if the value is true then it will be used to create CGLIB proxies.

exposeProxy: Indicates that proxy will be exposed via ThreadLocal for retrieval via AppContext class, default value is false, if the value is true then also AppContext will not guarantee for accessing proxy.

Enabling @AspectJ annotation using XML Configuration

Spring provides aop namespace for configuring proxy configuration. Find the link
<aop:aspectj-autoproxy />  
This xml tag also accepts the same attributes as specified above.

Declaring an aspect

After enabling AspectJ support we can declare the class with @AspectJ so that it will be auto-detected by spring AOP, but only @AspectJ annotation is not sufficient to auto-detect, if we are using XML Configuration then we need to declare the class as bean in application context, if we are using Java annotation then we need to annotate with any of the spring stereo types so that it will be auto detected and proxies will be generated.

Declaring Pointcut

Spring AOP only supports method execution jointpoint for spring beans, and pattern matching only apply on spring beans.
Pointcut declaration two parts.
1) Method signature which consists of name and parameters.
2) Expression/pattern on which methods we like to execute.
@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature  
The return type of the method annotated with @Pointcut must be void. The visibility doesn't affect the pattern matching.

Supported Pointcut Designators

Spring AOP supports below AspectJ pointcut designators in pointcut expression.

1) execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
2) within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
3) 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
4) 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
5) args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
6) @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
7) @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)
8) @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)
9) @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation call, get, set, preinitialization, staticinitialization, initialization, handler, adviceexecution, withincode, cflow, cflowbelow, if, @this, and @withincode these point-cut types supported Aspect Languages but not Spring AOP.
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).
Example: bean(idOrNameOfBean).

Declaring advice

Advice is associated with pointcut and can run before, after, around method executions as specified in configuration. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place.
package com.xyz.someapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

public class SystemArchitecture {
    @Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
    public void dataAccessOperation() {}
public class BeforeExample {

    public void doAccessCheck() {
        // ...
Or we can also directly use pointcut expression in before annotation.
public class BeforeExample {

    @Before("execution(* com.xyz.myapp.dao.*.*(..))")
    public void doAccessCheck() {
        // ...
XML Style of declaring Advices
    <aop:aspect id="myAspect" ref="aBean">
        <aop:pointcut id="businessService"
            expression="execution(* com.xyz.myapp.service.*.*(..)) && this(service)"/>
        <aop:before pointcut-ref="businessService" method="monitor"/>
<bean id="aBean" class="...">


Spring AOP is the framework for creating cross cutting patterns in spring beans, without modifying code we can implement additional behavior using aspects. Spring AOP supports both XML style and Java Annotated configuration. Spring AOP doesn`t supports the all features of Aspect languages features. As spring AOP is implemented using proxies it will only supports the runtime weaving of aspects.

This blog is about concept of spring Aspect Oriented Programming. If you have any doubt or want to ask anything, you may contact experts of java development India today. You can make comments below and wait for their response.

Download Source Code

About the Author
Johnny Morgan
Johnny Morgan

©2021 concretepage.com | Privacy Policy | Contact Us