[SSM framework] Spring notes - AOP details; Use of four notifications in AspectJ

1. Aspect oriented programming AOP

AOP (aspect oriented programming), aspect oriented programming.

Facet: the common, general and repeated functions are called facets. Facet oriented programming is to extract the facets, develop them separately, and weave them into the methods to be called through dynamic agents.

 

2. "Evolution" of AOP framework

1) The first version: business and aspect are tightly coupled without splitting

2) The second version: use subclass agent to split business and aspects

3) The third version: use static agent to split business and aspects Business and business interface have been split At this time, the facet is tightly coupled in the business

4) The fourth version: use static agent to split business and business interface, aspect and aspect interface

5) The fifth version: use dynamic agent to complete the optimization of the fourth version

 

3. Implementation of AOP supported by Spring

Spring supports AOP programming. The following are commonly used:

1)Before notification: called before the target method is called. The interface involved is org springframework. aop. MethodBeforeAdvice

2)After notification: called after the target method is called. The involved interface is org springframework. aop. AfterReturningAdvice

3)Throws notification: called when the target method throws an exception. The interface involved is org springframework. aop. ThrowsAdvice

4)Around notification: intercept method calls to the target object. The interface involved is org aopalliance. intercept. MethodInterceptor

 

4. Terms commonly used in AOP

1) Facet: those repeated, common and general functions are called facets, such as logs, transactions and permissions

2) Connection point: it is the target method Because the function and section function of the target method should be realized in the target method

3) Pointcut: specify the location of the pointcut. Multiple connection points constitute the pointcut. The pointcut can be a target method, all methods in a class, and all methods in all classes under a package

4) Target object: whoever operates is the target object

5) Advice: to specify the cut in time, whether before or after the execution of the target method, or in case of error, or around the cut in function of the target method
  

5. AspectJ framework

  • AspectJ is an excellent aspect oriented framework, which extends the java language and provides a powerful aspect implementation. Because it is developed based on java language, it extends seamlessly

 

There are four types of notifications commonly used in AspectJ:

1) Advance notice @ Before

2) Post notification @ AfterReturning

3) Surround notification @ Around

4) Final notification @ After

5) Define pointcut @ pointcut (understand)

 

6. Pointcut expression of AspectJ (Master)

Normative formula:

  • Execution (access permission method return value method declaration (parameter) exception type)

It can be simplified to:

  • Execution (method return value, method declaration (parameter))

Symbols used:

* stands for any (wildcard)
    .. If it appears in the parameters of the method, it represents any parameter; If it appears in the path, it represents the path and all its sub paths (in fact, it is equivalent to the ellipsis in the path)

 

Example:

//Any public method:

execution(public * *(..)) 

//Any method that starts with "set"

execution(* set*(..))

//Any return value type, on COM xyz. service. Any method of any class under impl package

execution(* com.xyz.service.impl.*.*(..))

//Any return value type, on COM xyz. Any method of any class under service and its sub package

execution(* com.xyz.service..*.*(..))

//There can be any sub package before the service

execution(* *..service.*.*(..))

//There was only one package before service

execution(* *.service.*.*(..))

 

7. Advance notice of AspectJ @ Before:

  • Cut into the facet function before the target method is executed. The return value of the target method cannot be obtained in the facet method, but only the signature of the target method can be obtained.

Implementation steps:

1) Add dependency:
   

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.5.RELEASE</version> 
</dependency>


2) Create business interface

3) Create business implementation

4) Create a facet class to implement the facet method

5) In ApplicationContext Slice binding in XML file

 

Chestnuts:

@Aspect  //Give AspectJ's framework to identify facet classes
@Component
public class MyAspect {
    /**
     * All facet functions are realized by facet method
     * Various aspects can be developed in this class
     *
     * Specification of aspect method of pre notification
     * 1)The access permission is public
     * 2)The return value of the method is void
     * 3)Method name customization
     * 4)Method has no parameters and can only be of JoinPoint type if any
     * 5)The @ Before annotation must be used to declare that the timing of the cut in is the pre cut function and the cut in point
     *   Parameter: value - specifies the pointcut expression
     *
     * Business method
     * public String doSome(String name, int age)
     */
    @Before(value = "execution(public String com.bjpowernode.s01.SomeServiceImpl.*(String,int))")
    public void myBefore(){
        System.out.println("Implementation of pre notification function in slice method............");
    }

    @Before(value = "execution(public * com.bjpowernode.s01.SomeServiceImpl.*(..))")
    public void myBefore(){
        System.out.println("Implementation of pre notification function in slice method............");
    }

    @Before(value = "execution( * com.bjpowernode.s01.*.*(..))")
    public void myBefore(JoinPoint jp){
        System.out.println("Implementation of pre notification function in slice method............");
        System.out.println("Signature of the target method:"+jp.getSignature());
        System.out.println("Parameters of the target method:"+ Arrays.toString(jp.getArgs()));
    }
    @Before(value = "execution( * com.bjpowernode.s01..*(..))")
    public void myBefore(){
        System.out.println("Implementation of pre notification function in slice method............");
    }

    @Before(value = "execution( * *(..))")
    public void myBefore(){
        System.out.println("Implementation of pre notification function in slice method............");
    }
}

 

AspectJ framework switches JDK dynamic agent and CGLib dynamic agent:

<!--Default is JDK Dynamic proxy, the interface type must be used when fetching-->
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>  
<!--Set to CGLib Subclass proxy, you can use interface and implement class connection, remember:Use the interface to connect and never make mistakes-->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>  

 

8. @ AfterReturning post notification:

  • Post notification is the function of cutting into the aspect after the target method is executed, and the return value of the target method can be obtained If the return value of the target method is a simple type (8 basic types + String), it cannot be changed If the return value of the target method is a reference type, it can be changed
        
@Aspect
@Component
public class MyAspect {
    /**
   * Specification of post notification method
   * 1)Access permission is public
   * 2)Method has no return value void
   * 3)Method name customization
   * 4)The method has parameters (or no parameters. If the target method has no return value, the method without parameters can be written, but generally with parameters, so that no parameters can be processed. The parameters of this aspect method are the return value of the target method
   * 5)Use the @ AfterReturning annotation to indicate a post notification
   *   Parameters:
   *      value:Specify pointcut expression
   *      returning:If you specify the name of the return value of the target method, the name must be consistent with the parameter name of the facet method
   */
    @AfterReturning(value = "execution(* com.bjpowernode.s02.*.*(..))",returning = "obj")
    public void myAfterReturning(Object obj){
        System.out.println("Implementation of post notification function..............");
        if(obj != null){
            if(obj instanceof String){
                obj = obj.toString().toUpperCase();
                System.out.println("The return value of the target method in the slice method:"+obj);
            }
            if(obj instanceof Student){
                Student stu = (Student) obj;
                stu.setName("Li Si");
                System.out.println("The return value of the target method in the slice method:"+stu);
            }
        }
    }
}

 

9. Surround notification @ Around:

  • It is a notification that enhances the function before and after the target method by intercepting the target method. It is the most powerful notification. General affairs use this notification It can easily change the return value of the target method

 

@Aspect
@Component
public class MyAspect {
    /**
     * Specification of surround notification method
     * 1)The access permission is public
     * 2)The facet method has a return value, which is the return value of the target method
     * 3)Method name customization
     * 4)Method has parameters, which is the target method
     * 5)Avoid exception Throwable
     * 6)Use the @ Around annotation to declare that it is a surround notification
     *   Parameters:
     *      value:Specify pointcut expression
     */

    @Around(value = "execution(* com.bjpowernode.s03.*.*(..))")
    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
        //Implementation of forward cutting function
        System.out.println("Implementation of pre function in surround notification............");
        //Target method call
        Object obj = pjp.proceed(pjp.getArgs());
        //Realization of back cutting function
        System.out.println("Implementation of post function in surround notification............");
        return obj.toString().toUpperCase();  //Changed the return value of the target method
    }
}

 

10. Final notification @ After

The final notification code will be executed whether the target method is executed normally or not

 

@Aspect
@Component
public class MyAspect {
    /**
     * Specification of final method
     * 1)The access permission is public
     * 2)The slice method does not return the value void
     * 3)Method name customization
     * 4)Method can have no parameters or parameters, then JoinPoint
     * 5)Use @ After annotation
     * 6)Parameter: value: specify pointcut expression
     */
    @After(value = "execution(* com.bjpowernode.s04.SomeServiceImpl.*(..))")
    public void myAfter(){
        System.out.println("The final notice is executed.............");
    }
}

 

11. Alias the Pointcut expression @ Pointcut

If multiple aspects cut into the same entry point, you can use aliases to simplify development. Use the @ Pointcut annotation to create an empty method whose name is an alias.
   

@Aspect
@Component
public class MyAspect {
    /**
   * Specification of final notification method
   * 1)The access permission is public
   * 2)Method has no return value
   * 3)Method name customization
   * 4)Method has no parameters and can only be JoinPoint if any
   * 5)Use the @ After annotation to indicate final notification
   *   Parameters:
   *     value:Specify pointcut expression
   */
    @After(value = "mycut()")
    public void myAfter(){
        System.out.println("Function of final notification........");
    }

    @Before(value = "mycut()")
    public void myBefore(){
        System.out.println("Pre notification function........");
    }

    @AfterReturning(value = "mycut()",returning = "obj")
    public void myAfterReturning(Object obj){
        System.out.println("Function of post notification........");
    }
    @Around(value = "mycut()")
    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Function of pre notification in surround notification........");
        Object obj = pjp.proceed(pjp.getArgs());
        System.out.println("Function of post notification in surround notification........");
        return obj;
    }

    @Pointcut(value = "execution(* com.bjpowernode.s04.*.*(..))")
    public void mycut(){}
}

 

Tags: Spring SSM

Posted by nlhowell on Thu, 26 May 2022 00:40:17 +0300