基于Spring的AOP切面编程

注解配置:

@Aspect
   要建立一个Aspect类,必须要有@Aspect注解代表是一个切面类。
   @Before   前置通知
   @After    后置通知
   @AfterReturning    返回通知
   @AfterThrowing      异常通知
   @Around    环绕通知

使得AspectJ注解起作用
<aop:aspect-autoproxy>
</aop:aspectj-autoproxy>

切面类变成要bean用 @Component
@Before("execution(public int com.iotek.cal.add(int,int))")
通配符
@Before("exexution(* com.iotek.cal.*(..))")
public   void    testBefore(JoinPoint   joinPoint){
            joinPoint.*
         System.out.println("前置通知");
}
@AfterReturning(value="execution(*com.iotek.*(..))",returning="result")
public void testAfter(JoinPoint join,Object result){
   System.out.println("返回通知","返回值:"+result);
}

@AfterThrowing(value="execution(*com.iotek.*(..))",throwing="e")
public void testAfterThrowing(JoinPoint joinpoint,Exception e){
      System.out.println("异常通知:"e.getMessage());
}

@Around("execution(*com.iotek.*(..))")
public Object testAround(ProceedingJoinPoint   pjp){
    Object result=0;
    System.out.println("前置通知");
    try{
        System.out.println("后置通知");
        result = pjp.procedd();
    System.out.println("返回通知");
    }catch(Throwable  throwable){
        System.out.println("异常通知");
    }
     return   result;
}


main{
ApplicationContext    context=new  ClassPathXmlApplicationContext(".xml");
接口   接口名=(接口类型)  context.getBean("切面类");

}


@Order(1)       代表,两个代理的优先级,数字越小优先越高

xml配置:

<bean id="calculator" class="com.iotek.Caluculator"></bean>
<bean id="restAspect" class="com.iotek.切面的功能类"></bean>

<aop:config>
    <aop:prointcut id="poi" expression=("execution(* com.iotek.Caluculator.*(..))")</aop:pointcut>
    <asp:aspect  ref="testAspect">
    <aop:before method="切面类方法名" pointcut-ref="pointcut"></aop:before>
    <aop:after-returning method="切面类方法名" pointcut-ref="pointcut" returning="切面类返回名"/>
    <aop:after-throwing method="切面类方法名"  pointcut-ref="pointcut" throwing="切面类异常名"/>
    <aop:after method="切面类方法名"  pointcut-ref="pointcut"></aop:after>
<aop:config>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值