Home » Spring AOP

Spring AOP

Last Updated on July 9, 2023 by KnownSense

Introduction

Spring AOP (Aspect Oriented Programming) compliments OOPs as it also provides modularity. But The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect

AOP breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-cutting concerns such as transaction management, authentication, logging, security etc. that cut across multiple types and objects.

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 Concepts

Aspect

A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).

Join point

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

Pointcut

A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut 

Introduction

Declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object.

Target object

object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.

AOP proxy

A proxy is an object that wraps another object maintaining its interface and optionally providing additional features. Proxies usually delegate behavior on the real object they are proxying but can execute code around the call to the wrapped object. AOP proxy is an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Weaving

Linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Advice

Action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point. There are different types of advice:

  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  • After throwing advice: Advice to be executed if a method exits by throwing an exception.
  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Spring AOP advice

Benefits

  • AOP is a great tool for keeping your codebase clean.
  • It allows you to keep your code focused on the main task at hand and extract all the cutting concerns to manageable pieces of code.
  • Enables Better Code Encapsulation and Reuse
  • It improves performance because the operations are more succinct. 

Real World Example

In our projects, We usually manage AOP using @AspectJ. This style of coding allows us to declare Pointcuts and Aspects using annotations.

In order to use AOP, we first need to select the points of our code where we want an aspect to be executed. This task is performed by writing a Pointcut. Example you wants logging some message before calling methods in the program.

@Aspect
@Component
public class logging {
	
	
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomSpanAspect.class);
    
     @Before("execution( * com.codingknownsense.user.controller..*.*(..)) || execution( * com.codingknownsense.user.dao..*.*(..)) "
    		+ "||  execution( * com.codingknownsense.user.service..*.*(..))")
public void beforeMethodExecution(JoinPoint joinPoint) {
			LOGGER.info("class:" + joinPoint.getSignature().getDeclaringType().getSimpleName()
					+ " to method: " + joinPoint.getSignature().getName()+ " with parameters as : " + getParamValues(joinPoint.getArgs()));
	}
}

The above code log the name of the class, method and arguments before executing any method inside the packages mentioned in @Before (i.e com.codingknownsense.user.controller, com.codingknownsense.user.dao, com.codingknownsense.user.service).

Similarly we can user @AfterReturning or @AfterThrowing to logs the result or error thrown by the method.
This helps in centralising the logging. It give a Standard format for all the logs in application. Developer didn’t need to add the logger in all the classes and can focus only on writing logic.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top