天天看點

Spring的AOP切面程式設計

語言蒼白無力,我們直接代碼說話

package com.example.demo.aspect;
import org.springframework.stereotype.Component;
@Component
public class AtithmeticCalulator {
  
  public int add(int a,int b){
    return a+b;
  }
  
  public int sub(int a,int b){
    return a-b;
  }
  
  public int mul(int a,int b){
    return a*b;
  }
  
  public int div(int a,int b){
    return a/b;
  }

}      

這是一個類,以方法add為例,當我們想在每一個方面前面添加一個告訴自己方法名和參數的時候,你會怎麼寫?

public int add(int a,int b){
    System.out.println("method mane:add    參數["+a+","+b+"]");
    return a+b;
  }      

有沒有感覺很麻煩,如果我四個方法都要用,你就要寫4遍

這個時候AOP派上用場

package com.example.demo.aspect;  
  
import java.util.Arrays;  
import java.util.List;  
  
import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.After;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.springframework.stereotype.Component;  
  
@Component//将元件加載到ioc容器,必須寫,否則加載不到ioc容器  
@Aspect//告訴ioc容器這是一個切面類,裡面有切面方法  
public class MyAspect {  
  
    //切面表達式public int com.example.demo.aspect.AtithmeticCalulator.*(int,int)  
    //包com.example.demo.aspect下的AtithmeticCalulator類所是public ,傳回值是int,參數是(int,int)的方法  
    @Before("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")
    public void before(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is begin:"+args);  
    }  
      
      
    @After("execution(public int com.example.demo.aspect.AtithmeticCalulator.*(int,int))")  
    public void after(JoinPoint joinPoint) {  
        String name=joinPoint.getSignature().getName();  
        List<Object> args=Arrays.asList(joinPoint.getArgs());  
        System.out.println("----the method "+name +" is close:"+args);  
    }  
      
      
  
}