Springboot:一个AOP切面快速入门示例

1.定义切面

(1)@Aspect注解修饰切面类
(2)@Pointcut注解定义切点
(3)@Around注解切点代理方法
(4)@Before注解定义执行切点前所要执行的方法
(5)@After注解定义执行切点后所要执行的方法

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class MyLogAspect {

	@Pointcut("execution(* controller.GoodsController.*(..)))")
	private void myLogPointcut(){

	}

	@Before("myLogPointcut()")
	private void before(JoinPoint joinPoint){
		System.out.println("进入方法前:" + joinPoint.getSignature().getName());
	}

	@After("myLogPointcut()")
	private void after(){
		System.out.println("方法执行完。。。。。");
	}

	/*@AfterReturning(value = "myLogPointcut()", returning = "returnVal")
	public void afterReturning(String returnVal){
		System.out.println("后置通知,返回参数:" + returnVal);
	}

	@AfterThrowing(value = "myLogPointcut()", throwing = "e")
	public void afterThrowing(Throwable e){
		System.out.println("异常通知,异常信息:" + e.getMessage());
	}*/

	@Around("myLogPointcut()")
	public Object around(ProceedingJoinPoint point){
		//获得方法名称
		Signature methodName = point.getSignature();
		System.out.println("进入方法:" + methodName);
		//让方法执行
		Object obj = null;
		try {
			obj=point.proceed(point.getArgs());
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
		return obj;
	}
}

2.执行切点对应的方法

调用Controller类里面的list方法

可以发现执行顺序是:around > before > list > after

3.总结说明

AOP的过程基本是首先定义一个切点,再对切点定义前后的执行方法,也比较简单。

本文介绍的切点只有execution,当然定义切点还有其他注解如@annotation,详细可以参考一下文章继续学习:

https://blog.csdn.net/Alinmei/article/details/123555553

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

行云的逆袭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值