AOP注解开发

目录

创建切面类并配置

@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("最终通知");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值