Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @Pointcut & @Before, @After AOP Annotations

Am learning AOP concepts in Spring. I am now pretty aware of the usages of @Before and @After Annotations and started using it for Time capturing purpose.

This is pretty much satisfying all my AOP related needs. Wondering what is that @pointcut annotation that every spring guide talks about ? Is that a redundant functionality ? or does it has separate needs ?

like image 906
Arun Avatar asked May 08 '17 09:05

Arun


People also ask

What is @pointcut in Java?

Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice.

What is @pointcut in Spring boot?

Pointcut: Pointcut is expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points and Spring framework uses the AspectJ pointcut expression language.

What is the difference between a join point and a pointcut?

A Joinpoint is a point in the control flow of a program where the control flow can arrive via two different paths(IMO : that's why call joint). A Pointcut is a matching Pattern of Joinpoint i.e. set of join points.


1 Answers

In simple words whatever you specify inside @Before or @After is a pointcut expression. This can be extracted out into a separate method using @Pointcut annotation for better understanding, modularity and better control. For example

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void requestMapping() {}

    @Pointcut("within(blah.blah.controller.*) || within(blah.blah.aspect.*)")
    public void myController() {}

    @Around("requestMapping() && myController()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
      ...............
   }  

As you can see instead of specifying the pointcut expressions inside @Around, you can separate it to two methods using @Pointcut.

like image 51
pvpkiran Avatar answered Oct 04 '22 23:10

pvpkiran