目录
创建切面类并配置
@Aspect定义为切面类
@Before:前置通知
@AfterReturning:后置通知
@Around:环绕通知
@AfterThrowing:异常通知
@After:最终通知
切入点配置
创建目标类并配置
创建切面类并配置
<!--开启aop注解开发--> <aop:aspectj-autoproxy/> <!--配置目标类--> <bean id="dao" class="com.aop.zhujie.Dao"/> <!--配置切面类--> <bean id="aspect" class="com.aop.zhujie.MyAspect"/>
@Aspect定义为切面类
@Aspect public class MyAspect
@Before:前置通知
@Before(value = "execution(* com.aop.zhujie.Dao.ff(..))") public void before(){ System.out.println("前置增强"); }
@AfterReturning:后置通知
@AfterReturning(value = "execution(* com.aop.zhujie.Dao.hh(..))",returning ="result") public void after(Object result){ System.out.println("后置增强"+result); }
@Around:环绕通知
@Around(value = "execution(* com.aop.zhujie.Dao.huanrao(..))") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("环绕前通知"); Object proceed = joinPoint.proceed();//加入原本的方法 System.out.println("环绕后通知"); return proceed; }
@AfterThrowing:异常通知
@AfterThrowing(value = "execution(* com.aop.zhujie.Dao.ec(..))",throwing = "throwable") public void ec(Throwable throwable){ System.out.println("异常通知"+throwable.getMessage()); }
@After:最终通知
:与后置通知的区别
他们俩都会放到目标方法的后面去执行,但是遇到异常,最终通知任然会执行
@After(value = "execution(* com.aop.zhujie.Dao.ec(..))") public void zuizhong(){ System.out.println("最终通知"); }
切入点配置
//切入点注解 @Pointcut(value ="execution(* com.aop.zhujie.Dao.ec(..))") public void Pointcut1(){};
应用:
@AfterThrowing(value = "MyAspect.Pointcut1()",throwing = "throwable") public void ec(Throwable throwable){ System.out.println("异常通知"+throwable.getMessage()); } @After(value = "MyAspect.Pointcut1()") public void zuizhong(){ System.out.println("最终通知"); }