Search code examples
javaaopspring-aop

What is the difference between an Aspect and a Method? [AOP]


I know this must be the most simple question ever, but as someone completely new to AOP i cant get my head around it.

  1. What is the difference between an Aspect and a Method?

within the documentation its mentioned:

Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.

"the modularizations of concerns" sounds to me like just making more methods for more specific procedures,

  1. is it? if not how any why is it different?

"that cut across multiple types and objects" sounds to me like these methods are global and able to be accessed from other classes, I'm near certain that this isn't correct. However the mention of Types and objects separately also has me a little confused here too.

  1. When objects are mentioned are these just POJO's?
  2. what is meant by Types if these aren't just objects?

Thanks in advance


Solution

  • Aspect is adding a behavior to a method (or all the classes of a method) through configuration instead of programmatically. The configuration can be done in XML, or anything else but the best example is with annotations, like for example you can have a method :

    @Audit
    public Integer doSomething(String parameter) {
        //Something is happening here
    }
    

    Simply adding the @Audit annotation will add the behavior of logging the input parameters, output value and the time of execution. And you do that by creating an interceptor and having your interceptor applied to the methods that have the annotation. This is just an example, you can implement transactions, caching, circuit breaker and a lot of other things with that.

    In your interceptor you have a normal method that take as parameter a ProceedingJoinPoint (assuming you are using AspectJ) which contains information about the method and on which you can call proceed() to actually call the method, this allow you to stuff before and after the method call, potentially changing arguments or return value and even potentially not calling the method at all (in the case of caching for example).

    The big benefit of aspects is that you write your interceptor once, and then it's very easy to add the behavior to any method you want through configuration.

    P.S. : When they say types and objects, I think you should understand it as interfaces and implementations, like you could add the behavior to all implementations of List or just to ArrayList.