Spring AOP Concepts

AOP Overview:- 

One of the key components of Spring Framework is the Aspect Oriented Programming (AOP) framework. 

Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns. These cross-cutting concerns are conceptually separate from the application's business logic. 

There are various common good examples of aspects such as logging, auditing, declarative transactions, security, caching, etc.

The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other, while AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others.

Spring AOP module lets interceptors intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution.

Spring AOP - Core Concepts

Before we start working with AOP, let us become familiar with the AOP concepts and terminologies. These terms are not specific to Spring, rather they are related to AOP.

Sr.No.

Terms & Description

1

Aspect

A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.

2

Join point

This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

3

Advice

This is the actual action to be taken either before or after the method execution. This is the actual piece of code that is invoked during program execution by Spring AOP framework.

4

PointCut

This is a set of one or more joinpoints where an advice should be executed. You can specify PointCuts using expressions or patterns as we will see in our AOP examples.

5

Introduction

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

6

Target object

The object being advised by one or more aspects. This object will always be a proxied object. Also referred to as the advised object.

7

Weaving

Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.

 

Spring AOP - Advice Types

Spring aspects can work with five kinds of advice mentioned in the following table.

Sr.No.

Advice & Description

1

before

Run advice before the method execution.

2

after

Run advice after the method execution, regardless of its outcome.

3

after-returning

Run advice after the method execution, only if the method completes successfully.

4

after-throwing

Run advice after the method execution, only if the method exits by throwing an exception.

5

around

Run advice before and after the advised method is invoked.

 

Spring AOP - Implementations

Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects.

1. XML Schema Based

Aspects are implemented using regular classes along with XML based configuration.

To use the AOP namespace tags described in this section, you need to import the spring AOP schema, described as follows −

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"

   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 

   xmlns:aop = "http://www.springframework.org/schema/aop"

   xsi:schemaLocation = "http://www.springframework.org/schema/beans

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 

   http://www.springframework.org/schema/aop 

   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <!-- bean definition & AOP specific configuration -->

</beans>

Declaring an Aspect

An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute as follows.

<aop:config>

   <aop:aspect id = "myAspect" ref = "aBean">

   ...

   </aop:aspect>

</aop:config>

<bean id = "aBean" class = "...">

   ...

</bean>

Here "aBean" will be configured and dependency injected just like any other Spring bean as you have seen in the previous chapters.

Declaring a Pointcut

A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with XML Schema based configuration, Pointcut will be defined as follows −

<aop:config>

   <aop:aspect id = "myAspect" ref = "aBean">


   <aop:pointcut id = "businessService"

      expression = "execution(* com.xyz.myapp.service.*.*(..))"/>

      ...

   </aop:aspect>

</aop:config>


<bean id = "aBean" class = "...">

   ...

</bean>

The following example defines a Pointcut named 'businessService' that will match the execution of getName() method available in Student class under the package com.javahubpoint.

<aop:config>

   <aop:aspect id = "myAspect" ref = "aBean">

   <aop:pointcut id = "businessService"

      expression = "execution(* com.javahubpoint.Student.getName(..))"/>

   ...

   </aop:aspect>

</aop:config>


<bean id = "aBean" class = "...">

   ...

</bean>

Declaring Advices

You can declare any of the five advices inside an <aop:aspect> using the <aop:{ADVICE NAME}> element as follows.

<aop:config>

   <aop:aspect id = "myAspect" ref = "aBean">

      <aop:pointcut id = "businessService"

         expression = "execution(* com.xyz.myapp.service.*.*(..))"/>

      <!-- a before advice definition -->

      <aop:before pointcut-ref = "businessService" 

         method = "doRequiredTask"/>

      <!-- an after advice definition -->

      <aop:after pointcut-ref = "businessService" 

         method = "doRequiredTask"/>

      <!-- an after-returning advice definition -->

      <!--The doRequiredTask method must have parameter named retVal -->

      <aop:after-returning pointcut-ref = "businessService"

         returning = "retVal"

         method = "doRequiredTask"/>

      <!-- an after-throwing advice definition -->

      <!--The doRequiredTask method must have parameter named ex -->

      <aop:after-throwing pointcut-ref = "businessService"

        throwing = "ex"

         method = "doRequiredTask"/>

      <!-- an around advice definition -->

      <aop:around pointcut-ref = "businessService" 

         method = "doRequiredTask"/>

   ...

   </aop:aspect>

</aop:config>


<bean id = "aBean" class = "...">

   ...

</bean>

You can use same doRequiredTask or different methods for different advices. These methods will be defined as a part of aspect module.

2. @AspectJ based

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. The @AspectJ support is enabled by including the following element inside your XML Schema-based configuration file.

<aop:aspectj-autoproxy/>

Declaring an Aspect

Aspects classes are like any other normal bean and may have methods and fields just like any other class, except that they will be annotated with @Aspect as follows.

package org.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect

public class AspectModule {

}

They will be configured in XML like any other bean as follows.


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

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

</bean>

Declaring a Pointcut

A Pointcut helps in determining the join points (i.e. methods) of interest to be executed with different advices. While working with @AspectJ based configuration, Pointcut declaration has two parts −

  • A Pointcut expression that determines exactly which method executions we are interested in.
  • A Pointcut signature comprising a name and any number of parameters. The actual body of the method is irrelevant and in fact should be empty.

The following example defines a Pointcut named 'businessService' that will match the execution of every method available in the classes under the package com.xyz.myapp.service.

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 

private void businessService() {}  // signature

The following example defines a Pointcut named 'getname' that will match the execution of getName() method available in Student class under the package com.javahubpoint.

import org.aspectj.lang.annotation.Pointcut;

@Pointcut("execution(* com.javahubpoint.Student.getName(..))") 

private void getname() {}

Declaring Advices

You can declare any of the five advices using @{ADVICE-NAME} annotations as given below. This assumes that you already have defined a Pointcut signature method businessService().

@Before("businessService()")

public void doBeforeTask(){

   ...

}

@After("businessService()")

public void doAfterTask(){

   ...

}

@AfterReturning(Pointcut = "businessService()", returning = "retVal")

public void doAfterReturnningTask(Object retVal){

   // you can intercept retVal here.

   ...

}

@AfterThrowing(Pointcut = "businessService()", throwing = "ex")

public void doAfterThrowingTask(Exception ex){

   // you can intercept thrown exception here.

   ...

}

@Around("businessService()")

public void doAroundTask(){

   ...

}

You can define Pointcut inline for any of the advices. Following is an example to define inline Pointcut for before advice.

@Before("execution(* com.xyz.myapp.service.*.*(..))")

public doBeforeTask(){

   ...

}