spring-aop(基于xml配置的形式)

切面源码

public class LoggingAspect {

    public void beforeMethod(JoinPoint joinPoint){
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(args);
    }


    public void afterMethod(JoinPoint joinPoint){
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("后置通知"+args);
    }


    public void afterReturning(JoinPoint joinPoint,Object result){
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"->"+result);
    }

    public void afterThrowing(JoinPoint joinPoint, Exception ex){
        String name = joinPoint.getSignature().getName();
        System.out.println("这是异常通知"+name+"->"+ex);
    }


    public Object aroundMethod(ProceedingJoinPoint pjd){

        String methodname = pjd.getSignature().getName();
        Object result = null;
        try {
            //这里相当于前置通知
            System.out.println("前置通知"+"->"+Arrays.asList(pjd.getArgs()));
            //执行目标方法
            result = pjd.proceed();
            //这里相当于返回通知
            System.out.println("返回通知"+"->"+result);
        } catch (Throwable throwable) {
            //这里相当于异常通知
            System.out.println("异常通知"+"->"+throwable);
            throw  new RuntimeException();
        }finally {
            //这里相当于后置通知
            System.out.println("后置通知"+"->"+methodname+"end");
        }
        return result;
    }

}

xml配置

  <!--配置bean-->
    <bean id="aitihmeticCalculatorImpl" class="AitihmeticCalculatorImpl"></bean>

    <!--配置切面的bean-->
    <bean id="loggingAspect" class="LoggingAspect"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置aop切点表达式-->
        <aop:pointcut id="pointcut" expression="execution(* AitihmeticCalculator.*(..))"></aop:pointcut>

        <!--配置切面及通知-->
        <aop:aspect ref="loggingAspect" order=1>
            <!--环绕-->
            <aop:around method="aroundMethod" pointcut-ref="pointcut"></aop:around>
            <!--前置-->
            <aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
            <!--后置-->
            <aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
            <!--返回-->
            <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
            <!--异常-->
            <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"></aop:after-throwing>
        </aop:aspect>
    </aop:config>
</beans>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值