Springboot中自定义注解实现AOP接口开发

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、增强方法执行顺序

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值