独自快乐|spring框架的入门学习:AOP和面向切面的事务( 六 )
spring的注解配置首先使用注解配置需要在xml中完成三步 , 其中前两步和前面一样 , 后面的一步是开启注解aop
配置好了 , 之后我们需要在通知对象中进行配置:
package com.huanfeng.annotationaop;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;//@Aspect表示这是一个通知类@Aspectpublic class MyAdvice {//前置通知@Before("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public void before(){System.out.println("这是前置通知!!");}//后置通知@AfterReturning("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public void afterReturning(){System.out.println("这是后置通知(如果出现异常不会调用)!!");}//环绕通知@Around("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public Object around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("这是环绕通知之前的部分!!");Object proceed = pjp.proceed();//调用目标方法System.out.println("这是环绕通知之后的部分!!");return proceed;}//异常通知@AfterThrowing("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public void afterException(){System.out.println("出事啦!出现异常了!!");}//后置通知@After("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public void after(){System.out.println("这是后置通知(出现异常也会调用)!!");}}我们每个通知都写一个execution太费事了 , 我们可以统一处理:
package com.huanfeng.annotationaop;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;//@Aspect表示这是一个通知类@Aspectpublic class MyAdvice {//前置通知@Pointcut("execution(* com.huanfeng.service.*ServiceImpl.*(..))")public void pc(){}@Before("MyAdvice.pc()")public void before(){System.out.println("这是前置通知!!");}//后置通知@AfterReturning("MyAdvice.pc()")public void afterReturning(){System.out.println("这是后置通知(如果出现异常不会调用)!!");}//环绕通知@Around("MyAdvice.pc()")public Object around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("这是环绕通知之前的部分!!");Object proceed = pjp.proceed();//调用目标方法System.out.println("这是环绕通知之后的部分!!");return proceed;}//异常通知@AfterThrowing("MyAdvice.pc()")public void afterException(){System.out.println("出事啦!出现异常了!!");}//后置通知@After("MyAdvice.pc()")public void after(){System.out.println("这是后置通知(出现异常也会调用)!!");}}
推荐阅读
- 快乐棒棒糖|众多男神女神加盟,看看有你期待的人吗,江苏晚会阵容曝光
- 董事长|华熙生物董事长:公司围绕“健康、美丽、快乐事业”不断投入
- 高管|华熙生物董事长:公司围绕“健康、美丽、快乐事业”不断投入
- 何伟|【高管面对面】华熙生物:保留初心 做健康美丽快乐事业
- 可馨说娱乐1|官宣加入恋综,萧亚轩动态轰动了,金莎发文“想体验萧亚轩快乐”
- 过得比我快乐|领土只能远远看着!,世界没有完成统一的3个发达国家
- 白夜追娱1|唯独不见黄明昊引热议,粉丝晒照片打脸黑粉,谢娜晒快乐家族合影
- 小海|原创玖月奇迹王小玮官宣离婚后,独自登上央视舞台,组合已经解散?
- 用智能引领快乐走进新的领域|古代名将能像影视剧游戏中一样挡住乱箭齐发吗?真有一个人能挡住
- 用智能引领快乐走进新的领域|结果悲剧了,网友称厉害了,皇帝竟娶了祖孙两代
