springboot简单配置自定义注解+AOP


一、AOP是什么?

AOP:面向切面编程
AOP底层核心:动态代理
动态代理底层核心: 反射

二、具体实现

1.自定义注解

@Target({ElementType.TYPE,ElementType.METHOD})//注解作用的位置
@Retention(RetentionPolicy.RUNTIME)//注解的生命周期
@Documented//是否添加java文档
public @interface MyAnno {
    String value() default "";
}

2.创建切面类


/**
 1. AOP类
 */
@Aspect
@Component
public class DSAspect {

    @Pointcut("@annotation(com.fdong.springboot.customAnnotation.annotation.MyAnno)")//切入点 自定义注解
    public void pointCut(){}
    // 前置通知
    @Before("pointCut()")
    public void doBefore(){
        System.out.println("执行了before方法....");
    }

    //不管有没有异常都执行  最终通知
    @After("pointCut()")
    public void doAfter(){
        System.out.println("执行了after....");
    }

    //后置通知  完成通知  有异常不执行
    @AfterReturning("pointCut()")
    public void doAfterReturning(){
        System.out.println("执行了doAfterReturning方法....");
    }

    //异常通知
    @AfterThrowing("pointCut()")
    public void doAfterThrowing(){
        System.out.println("执行AfterThrowing方法....");
    }

    //环绕通知,灵活添加代码
    @Around("pointCut() && @annotation(myAnno)")
    public void doAround(ProceedingJoinPoint proceedingJoinPoint, MyAnno myAnno) throws Throwable {
        System.out.println("执方法doAround前....");
        System.out.println("获得自定义注解参数value:"+myAnno.value());
        String methodName = proceedingJoinPoint.getSignature().getName();
        System.out.println("注解作用的方法名:"+methodName);
        proceedingJoinPoint.proceed();
        System.out.println("执方法doAround后....");
    }
}

3.使用

  1. 控制器层
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    public void test(){
        System.out.println("***************TestController test");
        testService.test();
    }

}

2.业务层

@Service
public class TestService {
    @MyAnno("执行MyAnno")
    public void test(){
        System.out.println("执行了TestService中的test方法");
    }
}

3.测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值