Spring usage - AOP

Posted by skeener on Sun, 21 Jun 2020 08:45:21 +0200

1, What is the role of AOP

Through AOP, we can isolate all parts of the business logic, so as to reduce the coupling between various modules.
At the same time, we can add new functions to the backbone functions without modifying the source code

Underlying principle

Dynamic proxy used

Dynamic agents are divided into two categories:

  • JDK proxy: enhance the target method by implementing the same interface as the target class
  • CGLIB: enhance the target by inheriting the target class

2, AOP terminology

  • Connection points: methods that can be enhanced
  • Entry point: the way we want to enhance
  • Notification: code extracted from logical code
  • Facets: encapsulation classes for notifications

3, AOP operation

You can do both of the following

1.1 enable AOP auto proxy with XML

<aop:aspectj-autoproxy/>

1.2 use annotation class to open auto proxy

@Import(EnableAspectJAutoProxy.class)

principle

We imported EnableAspectJAutoProxy to the container through @ Import. This class implements the importbeandefinitionregister interface, which will be executed by a callback when the container post processor executes. In this callback method, this class registers the AnnotationAwareAspectJAutoProxyCreator class with our container. The AnnotationAwareAspectJAutoProxyCreator class also implements our postprocessor interface in the parent class, so this class will be called every time we create a Bean, that is to say, this class will complete the proxy before the target Bean is initialized according to our configured cut-off point and cut-off point.

2. Write cut class

@Aspect
@Component
public class MyAspect {
    @Pointcut("execution(* com.xmlSpring.beans.*.*(..))")
    void cutPoint(){}

    @Before("cutPoint()")
    public void beforeProcessor(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        System.out.println("solider "+args[1].toString()+" has been built");
    }

    @AfterReturning(value = "cutPoint()",returning = "obj")
    public void afterReturningProcessor(JoinPoint joinPoint,Object obj){
        System.out.println(obj);
    }

    @AfterThrowing(value = "cutPoint()",throwing = "ex")
    public void afterThrowingProcessor(JoinPoint joinPoint,Exception ex){
        System.out.println(ex.getMessage());
    }

    @After(value = "cutPoint()")
    public void afterProcessor(JoinPoint joinPoint){

    }

    @Around(value = "cutPoint()")
    public void after(ProceedingJoinPoint joinPoint)  {
        try{
            System.out.println("before");
            joinPoint.proceed();
            System.out.println("afterReturning");
        }catch (Throwable throwable){
            System.out.println("throwing");
        }finally {
            System.out.println("after");
        }
    }
}

Where our @ Pointcut annotation represents the common tangent point

There are five kinds of notices

  • @Before: advance notice
  • @After: Post notification, equal to finally
  • @AfterReturning: Post return notification, equal to return
  • @AfterThrowing: exception notification, equal to catch
  • @Around: around notification

be careful:

  • Our previous notifications can only record parameters, call methods, etc. But the return value of the enhanced object cannot be changed
    If we need to change the content of the return value, we need to use surround notification
  • If the JointPoint parameter needs to be put in the parameter, it needs to be in the first
    With this parameter, we can get the method name and parameter array
  • When we have multiple facets, they will execute. If we need to execute in a certain Order, we must add @ Order annotation. The smaller the number, the greater the priority

3. Configuration of section class

  • @Aspect: as mentioned above
  • Configuring in xml

Now let's introduce the second one

The usage is the same as the annotation, but the setting is different

Here is just an example of before. Others are almost the same. Interested friends can study more by themselves

<!--aspect Class-->
    <bean id="aspect1" class="com.xmlSpring.aspects.MyAspect"/>
    
    <!--aspect class config-->
    <aop:config>
        <aop:aspect ref="aspect1">
            <aop:pointcut id="pc" expression="execution(* com.xmlSpring.beans.*.*(..))"/>
            <aop:before method="beforeProcessor" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>

 

Topics: xml JDK