AOP的使用

spring中的aop如何使用

1.AOP的使用场景

在实际工作中,可能会存在需要在调用方法前后做一些处理,例如:
1>调用业务方法前,检验入参信息,来决定后续方法执行的逻辑;
2>调用业务方法后,日志信息的记录等。

2.JoinPoint 介绍

JointPoint是程序运行过程中可识别的点,这个点可以用来作为AOP切入点。JointPoint对象则包含了和切入相关的很多信息。比如切入点的对象,方法,属性等。在这里插入图片描述

aop的简单使用

1>引入注解:

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
 package com.atguigu.mybatisplus.AOP;

2>创建注解:

package com.atguigu.mybatisplus.AOP;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnno {
}


2>编写切面逻辑:

package com.atguigu.mybatisplus.AOP;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class VerifyAnnoAspect {

    @Pointcut("@annotation(com.atguigu.mybatisplus.AOP.TestAnno)")
    public void point(){}

    @Around(value = "point()")
    public void around(ProceedingJoinPoint joinPoint)throws Throwable{
        System.out.println("环绕方法执行前。。。");
        joinPoint.proceed();//调用要切的方法
        System.out.println("环绕方法后......");
    }

    @Before("point()")
    public void before() {
        System.out.println("调用方法前执行。。。");
    }

    @After(value = "point()")
    public void after(JoinPoint joinPoint)throws Throwable{
        System.out.println("调用方法后执行。。。");
    }

    @AfterReturning(value = "point()")
    public void afterReturning(JoinPoint joinPoint)throws Throwable{
        System.out.println("调用方法返回结果后执行。。。");
    }



}

4.编写controller

package com.atguigu.mybatisplus.AOP;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {


    @GetMapping ("/aaa")
    @TestAnno
    public void aaa(){
        System.out.println("测试的方法");
    }
}

5.测试:
输入localhost:80800/aaa

结果:

环绕方法执行前。。。
调用方法前执行。。。
测试的方法
调用方法返回结果后执行。。。
调用方法后执行。。。
环绕方法后......

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值