Understanding Spring AOP

spring aop example
spring boot aop example
spring aop logging
when to use spring aop
spring aspect example
spring 5 aop
spring aop interview questions
spring aspectj

AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. This modification can be done before the classes are put into a jar/war, or can happen dynamically while the code is being loaded.

The idea is, rather than finding all the points of code that you want to modify in the source code and hand modifying them, you define rules for how to find points of interest in the code base, and what embellishments you would like to do to them. These rules are called aspects (the A of AOP).

The prototypical example is you want to get some timing information on various methods in your code base. You could go find all the methods of interest and at the top put a call to

long start = System.currentTimeMillis();

and at the end do

long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));

but that is:

  1. probably a bunch of work
  2. temporary, and you don't want to muck up your code base

You can instead define aspects that say what methods you want to modify, and that you want to do stuff at the beginning and end of these methods.

When the AOP is applied, either at jar creation time, or class loading time, it's as if you wrote the classes that way originally.

Understanding Spring AOP, AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. The most basic concept that we need to understand how AOP works in Spring is that of a Proxy. A proxy is an object that wraps another object maintaining its interface and optionally providing

AOP is a pattern used to modularize cross cutting features. So if there is a certain "thing" that applies to a significant part in your code then you can use AOP to solve that problem. These "things" are called aspects.

An example below:

An exception logger is used across the enterprise app. So you could set it up using AOP the following way. So now all methods under my.service package will get logged the following way.

  <bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
                <aop:pointcut id="allServiceMethods" expression="execution(* my.service.*(..))" />
                <aop:aspect id="serviceLogger" ref="exceptionLogger">
                    <aop:after-throwing pointcut-ref="allServiceMethods"

And the ExceptionLogger class could be something like below:-

public class ExceptionLogger {
    private static Logger logger = Logger.getLogger(ExceptionLogger.class);
    public void logIt(JoinPoint jp, Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("<whatever makes sense>");

Also take a look at this relevant question:-

  1. What is the most common use for AOP in spring project

Understanding Spring AOP, It is important to grasp the fact that Spring AOP is proxy-based. See the section entitled Section 6.6.1, “Understanding AOP proxies” for a thorough examination  In this article, we will understand Spring AOP concepts and terminology with step by step example. AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code without modification of the code itself.

Aspect Oriented Programming is sensibly new and it is not a replacement for Object Oriented Programming. In fact, AOP is another way of organizing your Program Structure.

To be more clear I will use some diagrams:

  1. What is Aspect?

    |      Aspect         =     Point cut    +  Advice          |
    |                     | Where the aspect | What code is     |
    |                     |  is applied      |  executed.       |

    Aspect = Point cut + Advice

  2. Type of Advice methods

  3. Aspect Example

    @Around( "execution(* *(..))" )
    public Object trace(ProceedingJoinPointproceedingJP)throwsThrowable{
        String methodInformation= proceedingJP.getStaticPart().getSignature().toString();
        logger.trace("Entering "+methodInformation);
        } catch(Throwable ex) {
            logger.error("Exception in "+methodInformation, ex);
            throw ex;
        } finally {
             logger.trace("Exiting "+methodInformation);

Chapter 6. Aspect Oriented Programming with Spring, uses either JDK proxies (preferred wheneven the proxied target implements at least one interface) or CGLIB proxies (if the target object does not implement any interfaces) to create the proxy for a given target bean. Spring provides declarative programming with AOP. This is a better way to implement cross cutting concerns without the needs to use plumbing code all over the core business classes. AOP enables you to think about concerns or aspects in your system.

Introduction to Spring AOP, , when a method is executed, you can add extra functionality before or after the method execution. In Spring AOP, a subclass is created at runtime where the target method is overridden and advices are included based on their configuration. Proxy: It is an object that is created after applying advice to the target object. In clients perspective, object, the target object, and the proxy object are same.

In a nutshell, AOP is a mathematician's way of explaining how you should organize your code neatly to avoid having a particular functionality scattered in bits and pieces across lots of modules or object. At its heart, AOP is a good thing whether or not it is called AOP.

But you are faced with a specific AOP implementation and need to figure out how to use it. I think the best way to do this is to look for blogs where people post recipes and examples of how they are using it with Spring. This way you bypass the mathemeticians and get to read the writings of engineers who are more in touch with reality.

There are two kinds of computer scientists, mathematicians who delight in the obscure and use tortured terminology to explain simple things, and engineers who will tell you step by step how to build software. Working programmers tend to be more of the engineer mindset because abstract thinkers find it hard to handle the long slog of gaining experience. That's why you find AOP hard to understand. Not because it is hard to understand, but because it is explained so poorly by abstract mathematical thinkers who are not terribly familiar with "plain English".

I wonder what would happen if an AOP guru sat down with a Function Point Analysis guru.

How Spring aspects work internally?, , aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects (often termed crosscutting concerns). Introduction to Spring AOP 1. Introduction. In this tutorial, we’ll introduce AOP (Aspect Oriented Programming) with Spring and start understanding 2. Overview. AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting 3. Maven Dependencies. The

AOP with Spring Framework, of aspects by creating proxy of the target objects. Spring AOP Implementation. Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides modularity. But the key unit of modularity is aspect than class. AOP breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-cutting concerns. A cross-cutting concern is a concern that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication,

Spring AOP Tutorial Example, Spring AOP enables Aspect-Oriented Programming in spring applications. In AOP, aspects enable the modularization of concerns such as transaction  Spring AOP Overview Most of the enterprise applications have some common crosscutting concerns that are applicable to different types of Objects and modules. Some of the common crosscutting concerns are logging, transaction management, data validation, etc.

What is 'weaving'?, This article on Spring AOP Tutorial will help you understand various aspects, types of advices etc. It will also take you through AspectJ  Spring calls the method accountService () every time it needs to wire an instance of the bean “accountService” and this one returns a “new” object of type AccountService. If 10 beans are using a dependency of type AccountService, this method is called 10 times.