Spring AOP Aspect Oriented notes in @Aspect uses detailed

introduction:

       AOP is an abbreviation for Aspect Oriented Programming, meaning: Aspect Oriented Programming, by way of pre-compiled and run-time dynamic agent uniform maintenance procedures for the functions of a technology .AOP is a continuation of OOP, is a hot spot in software development, but also an important element in the Spring framework is a functional programming Yan Shengfan type. AOP can use to isolate each part of the business logic such that the business logic to reduce the degree of coupling between the parts, improve the reusability of the program, while improving efficiency of development.

       In Spring AOP business logic just only focus on the business itself, logging, performance statistics, security control, transaction processing, exception handling code is divided from the business logic code, by separating these actions, we hope they can be independent non-directive method to business logic, and thus change the behavior of the time does not affect the business logic code.

A comment as follows:

@Aspect: the role of the current class is identified as a read section for the container
 
@Pointcut: Pointcut trigger condition is implanted Advice of. The definition of each Pointcut include two parts, one is the expression, the second is the method signature. The method signature must be public and void type. Pointcut method can be seen as a mnemonic cited Advice, because the expression is not intuitive, so we can pass the method signature name for this way of expression. Therefore, the only method Pointcut method signature, without the need to write the actual code in the method body.
@Around: Surround enhancements, the equivalent of MethodInterceptor
@AfterReturning: Rear enhanced, equivalent to AfterReturningAdvice, perform a method exits normally
@Before: identifying a pre-enhancement methods, BeforeAdvice equivalent function, as well as a similar function
@AfterThrowing: Enhanced exception is thrown, the equivalent of ThrowsAdvice

 A: the introduction of its dependencies

  

II: the profile applicationContext.xml Spring introduced context, aop corresponding namespace; configuration automatically scan packages, while the annotations related aspect class method into effect, where the class for an automatically matched to a method for generating agent object.

   

3, create a simple calculator interface and implementation class ArithmeticCalculatorImpl.java ArithmeticCalculator.java

package com.svse.aop;

public interface ArithmeticCalculator {

    // define four simple arithmetic algorithm excuse 
    int the Add ( int i, int J);

    int sub(int i, int j);

    you executed ( you 's, you j);

    int div(int i, int j);
}
package com.svse.aop;
import org.springframework.stereotype.Component;

// implementation classes added Spring's IOC container management 
@Component ( "arithmeticCalculator" )
 public  class ArithmeticCalculatorImpl the implements ArithmeticCalculator {

    @Override
    public int add(int i, int j) {
         int result = i + j;
            return result;
    }

    @Override
    public int sub(int i, int j) {
          int result = i - j;
            return result;
    }

    @Override
    public int mul(int i, int j) {
          int result = i * j;
            return result;
    }

    @Override
    public int div(int i, int j) {
          int result = i / j;
            return result;
    }

}

4, now want to implement methods before each class after the execution, and print out the abnormality information, the need to extract information out of the log, written to a corresponding class LoggingAspect.java section has occurred in
order to put a class cut into categories, two steps,
① using @Component annotation on the aspect class category is added to the vessel IOC
② @Aspect annotation used in making the aspect class class

package com.svse.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import com.tencentcloudapi.vod.v20180717.VodClient;

/**
 * Log section
 * 
 * @author zhaoshuiqing<br>
 * 3:03:29 @date 2019 Nian 6 14 afternoon
 */
@Component
@Aspect
public class LoggingAspect {

    // Before executing want to implement each method in the class now, after, and whether to print out information such as abnormal occurs, you need to log information extracted, write to the corresponding section of the class LoggingAspect.java in 
     // order to cut into a class-based, two steps, 
     // ① use @Component annotation on the aspect class category is added to the vessel IOC 
     // ② @Aspect annotation used in making the aspect class class
    
    
    /**
     * Before advice: Perform the following method body of content before the target method of execution 
     * @param jp
     */
    @Before("execution(* com.svse.aop.*.*(..))")
    public void beforeMethod(JoinPoint jp){
         String methodName =jp.getSignature().getName();
         System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
    }
    
     /**
     The following code execution when the target method normally finished: * Back Tell
     * @Param jp
     * @param result
     */
    @AfterReturning(value="execution(* com.svse.aop.*.*(..))",returning="result")
    public void afterReturningMethod(JoinPoint jp, Object result){
         String methodName =jp.getSignature().getName();
         System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
    }
    
      /**
     * After returning advice: Perform the following method body of content after the target method executes, regardless of whether an exception occurs.
     * @param jp
     */
    @After("execution(* com.svse.aop.*.*(..))")
    public void afterMethod(JoinPoint jp){
        System.out.println("【后置通知】this is a afterMethod advice...");
    }
    
    

    /**
     * Exception notification: target method exception occurs when the following code is executed
     */
    @AfterThrowing(value="execution(* com.qcc.beans.aop.*.*(..))",throwing="e")
    public void afterThorwingMethod(JoinPoint jp, NullPointerException e){
         String methodName = jp.getSignature().getName();
         System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
    }
    
    
  /**
  * Around advice: before and after the target method were performed to execute some code executed when the exception occurred some other codes
  * @return 
  */
 /*@Around(value="execution(* com.svse.aop.*.*(..))")
 public Object aroundMethod(ProceedingJoinPoint jp){
     String methodName = jp.getSignature().getName();
     Object result = null;
     try {
         System.out.println ( "[surrounded notification ---> Pre-notification]: the method [" + methodName + "] begins with" + Arrays.asList (jp.getArgs ()));
         // execute the target method
         result = jp.proceed();
         System.out.println ( "[surrounded notification ---> return notification]: the method [" + methodName + "] ends with" + result);
     } catch (Throwable e) {
         System.out.println ( "[surrounded notification ---> abnormality notification]: the method [" + methodName + "] occurs exception" + e);
     }
     
     System.out.println ( "[surrounded notification ---> after advice}: ----------------- end .---------- ------------ ");
     return result;
 }*/

}

   5, the test method to write MainTest

package com.svse.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public  class MainTest {

    public static void main(String[] args) {
        
        // ClassPathXmlApplicationContext default is to load the xml file in the src directory 
        ApplicationContext ctx = new new ClassPathXmlApplicationContext ( "applicationContext.xml" );
        ArithmeticCalculator arithmeticCalculator =(ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
        
        System.out.println(arithmeticCalculator.getClass());
        int result = arithmeticCalculator.add(3, 5);
        System.out.println("result: " + result);
        
        result = arithmeticCalculator.div(5, 0);
        System.out.println("result: " + result);
    }

}

operation result:

  

The code is commented other, surrounded by the method of notification is released, the test results are as follows:

So far AOP Aspect Oriented comment on logging finished!

Guess you like

Origin www.cnblogs.com/zhaosq/p/11018081.html