springBoot 集成 AOP

一、AOP 概念

        面向切面编程,通过预编译方式和运行期动态代理实现程序功能统一维护的一种技术。

二、编码

2.1 添加 maven 依赖

<!-- spring boot支持aop -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.2 编写 aop 切面类

/*
	@Aspect:表明这是一个切面类
	@Pointcut:切入点,后面的execution是用于使用切面的连接点
	@Before:在方法前执行
	@After:在方法后执行
	@AfterReturning:在方法执行后返回一个结果后执行
	@AfterThrowing:在方法执行过程中抛出异常后的时候执行
	@Around:环绕通知,可以在执行前后都使用,这个方法的参数必须为ProceedingJoinPoint,proceed()方法就是被切面的方法,
		上面四个方法可以使用JoinPoint,JoinPoint包含了类名,被切面的方法,参数等信息。
 */
@Aspect
@Component
public class TestAspectUtil {

	@Pointcut("execution(public * com.aop.*.*(..))")
    public void TestAspect(){
		
	}
	
	@Before("TestAspect()")
    public void doBefore(JoinPoint joinPoint){
        System.out.println("执行前置通知");
    }

    @After("TestAspect()")
    public void doAfter(JoinPoint joinPoint){
        System.out.println("执行后置通知");
    }

    @AfterReturning("TestAspect()")
    public void doAfterReturning(JoinPoint joinPoint){
        System.out.println("执行返回后通知");
    }

    @AfterThrowing("TestAspect()")
    public void deAfterThrowing(JoinPoint joinPoint){
        System.out.println("执行抛出异常后通知");
    }

    @Around("TestAspect()")
    public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("执行环绕通知!");
        //继续执行被代理的方法
        return joinPoint.proceed();
    }
}

2.3 编写 controller 类

@RestController
public class TestAopController {

	/**
	 * @GetMapping: 是一个组合注解,是 @RequestMapping(method=RequestMethod.GET) 的缩写
	 * @PostMapping:是一个组合注解,是 @RequestMapping(method=RequestMethod.POST) 的缩写
	 */
	@GetMapping("/aopIndex")
	public String index() {
		System.out.println("方法aopIndex执行");
		return "hello world";
	}
}

2.4 项目结构

三、测试

        启动项目,在浏览器输入 http://localhost:8080/aopIndex

        控制台的输出如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐的小三菊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值