1、自定义一个注解
package com.example.demo.wb;
import java.lang.annotation.*;
//自定义注解,名叫WB
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface WB {
}
2、在需要aop拦截的方法上添加自定义的注解,我这里是添加到Controller上
package com.example.demo.wb;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@WB
@RequestMapping("/myrequest")
public String doRequest(){
return "Controller已处理";
}
}
3、编写AOP接口,最最最关节的注解是@Aspect
package com.example.demo.wb;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAop {
//切面连接处
@Pointcut("@annotation(com.example.demo.wb.WB)")
public void cutMethod(){}
@Before(value="cutMethod()")
public void doBeforeCut(JoinPoint joinPoint) throws Exception {
//JoinPoint用于获取被切入面的方法名,参数等信息
//String methodName=JoinPoint.getSignature().getName();
//获取请求属性
// ServletRequestAttributes attributes =
// (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// //获取请求对象
// HttpServletRequest request = attributes.getRequest();
/**
* 下面可做其他验证操作
*/
System.out.println("Before增强方法");
}
@Around(value="cutMethod()")
public Object doAroundCut(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//ProceedingJoinPoint只能在around增强方法中使用,与JoinPoint类似
System.out.println("Around增强方法");
//Around方法里不设置如下返回值,被切入面的方法也无法返回信息,如我这里是切入Controller,那么不设置返回,则Controller无法返回信息
Object returnValue=proceedingJoinPoint.proceed(); //执行目标方法
return returnValue;
}
@AfterReturning(value="cutMethod()")
public void doAfterReturningCut(JoinPoint joinPoint){
System.out.println("AfterReturning增强方法");
}
@After(value ="cutMethod()")
public void doAfterCut(JoinPoint joinPoint){
System.out.println("After增强方法");
}
@AfterThrowing(value = "cutMethod()")
public void doAfterThrowingCut(JoinPoint joinPoint){
System.out.println("AfterThrowing增强方法");
}
}
4、postman测试,发一个请求
请求执行顺序
5、增强方法执行顺序