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);
}
}
运行结果所示: