This Halloween Pikachu follows your mouse or screen taps

Spring Aspectj的AOP使用

Aspectj可以很方便地实现AOP,不用繁琐的写各种配置文件。

切入点表达式

语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)

  • 修饰符,可以省略

    • public
    • * 任意
  • 返回值,不能省略

    • * 任意

  • com.itheima.crm 固定包
    com.itheima.crm.*.service 代表com.itheima.crm包下面子包任意包下的service类
    com.itheima.crm… 代表crm包下面的所有子包(含自己)
    com.itheima.crm.*.service… crm包下面任意子包,固定目录service,service目录任意包


  • UserServiceImpl 指定类
    *Impl 以Impl结尾
    User* 以User开头
    * 表示任意

  • 方法名
    addUser 固定方法
    add* 以add开头
    *Do 以Do结尾

    * 任意

  • 参数

    (…) 参数任意

  • throws ,可省略,一般不写。

within:匹配包或子包中的方法

this:匹配实现接口的代理对象中的方法

target:匹配实现接口的目标对象中的方法

args:匹配参数格式符合标准的方法

bean(id):对指定的bean所有的方法

AspectJ 通知类型

6种,这里展示5种常用的。

  • before:前置通知(应用:各种校验)
    在方法执行前执行,如果通知抛出异常,阻止方法运行
  • afterReturning:后置通知(应用:常规数据处理)
    方法正常返回后执行,如果方法中抛出异常,通知无法执行
    必须在方法执行后才执行,所以可以获得方法的返回值。
  • around:环绕通知(应用:十分强大,可以做任何事情)
    方法执行前后分别执行,可以阻止方法的执行
    必须手动执行目标方法
  • afterThrowing:抛出异常通知(应用:包装异常信息)
    方法抛出异常后执行,如果方法没有抛出异常,无法执行
  • after:最终通知(应用:清理现场)
    方法执行完毕后执行,无论方法中是否出现异常

Around可以实现各种其他类型:

try{
    //前置:before
    //手动执行目标方法
    //后置:afterReturning
} catch(){
    //抛出异常 afterThrowing
} finally{
    //最终 after
}

切面类模板:

/**
 * 切面类,含有多个通知
 */
@Component
@Aspect
public class MyAspect {
	
	//声明公共切入点
	@Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
	private void myPointCut(){
	}
	
    //切入点当前有效
	@Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
	public void myBefore(JoinPoint joinPoint){
		System.out.println("前置通知 : " + joinPoint.getSignature().getName());
	}
    
//	@AfterReturning(value="myPointCut()" ,returning="ret")
	public void myAfterReturning(JoinPoint joinPoint,Object ret){
		System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
	}
	
//	@Around(value = "myPointCut()")
	public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("前");
		//手动执行目标方法
		Object obj = joinPoint.proceed();
		
		System.out.println("后");
		return obj;
	}
	
//	@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
	public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
		System.out.println("抛出异常通知 : " + e.getMessage());
	}
	
	@After("myPointCut()")
	public void myAfter(JoinPoint joinPoint){
		System.out.println("最终通知");
	}

}

转:https://blog.csdn.net/qq_43650773/article/details/85019629

posted @   图图雷  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示