一、获取方法名、参数值、参数值类型、目标注解对象、目标方法所在类
1、引入pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、创建一个自定义注解类CacheableTest
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CacheableTest {
String key();
String value() default "";
int expireTime() default 3600;
}
3、创建一个controller类,并加入该方法:
@RequestMapping("/findPage2")
@CacheableTest(key="haha",value = "hehe")
public String findPage2(Integer pageNumber, Integer pageSize){
System.out.println("findPage2请求成功!!!");
return "请求成功";
}
4、创建一个切面类TestAop:
@Component
@Aspect
public class TestAop {
@Pointcut("execution(public * com.wang.controller.TestController.*(..))") //第一个星号指返回值类型为任意
private void pointCut(){};
@Before(value = "pointCut()")
public void logBefore(JoinPoint joinpoint) {
System.out.println("----------Before开始-----------");
System.out.println("方法名:"+ joinpoint.getSignature().getName());
System.out.println("参数值集合:"+ Arrays.asList(joinpoint.getArgs()));
System.out.println("参数值类型:"+ joinpoint.getArgs()[0].getClass().getTypeName());
//获取目标注解对象,CacheableTest是自定义的一个注解
CacheableTest cacheable = ((MethodSignature)joinpoint.getSignature()).getMethod().getAnnotation(CacheableTest.class);
String classType = joinpoint.getTarget().getClass().getName();
System.out.println("目标注解对象:"+ cacheable);
System.out.println("获取目标方法所在类:"+ classType);
System.out.println("----------Before结束-----------");
}
@After(value = "pointCut()")
public void logAfter(JoinPoint joinpoint) {
System.out.println("---------After开始------------");
System.out.println("---------After结束-------------");
}
}
执行结果:
二、环绕通知:
(注意:该方法只有返回了point.proceed()后,执行接口方法后才会有返回值!)
@Around(value = "pointCut()")
public Object logBefore(JoinPoint joinpoint) throws Throwable {
System.out.println("----------环绕开始-----------");
System.out.println("方法名:"+ joinpoint.getSignature().getName());
System.out.println("参数值集合:"+ Arrays.asList(joinpoint.getArgs()));
System.out.println("参数值类型:"+ joinpoint.getArgs()[0].getClass().getTypeName());
//获取目标注解对象,CacheableTest是自定义的一个注解
CacheableTest cacheable = ((MethodSignature)joinpoint.getSignature()).getMethod().getAnnotation(CacheableTest.class);
String classType = joinpoint.getTarget().getClass().getName();
System.out.println("目标注解对象:"+ cacheable);
System.out.println("获取目标方法所在类:"+ classType);
ProceedingJoinPoint point = (ProceedingJoinPoint) joinpoint;
System.out.println("----------环绕结束-----------");
return point.proceed(); //放行,执行接口方法
}