欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring基础---AOP使用拓展

程序员文章站 2022-07-12 12:55:06
...

一、使用注解定义切面

1、定义切面
Spring基础---AOP使用拓展

2、在spring配置文件启用 aspectj 注解

<!-- 在头文件引入 aop xmlns:aop="http://www.springframework.org/schema/aop"
                    xsi:schemaLocation="http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd" -->
<!-- 生成一个增强类的实例 -->
<bean id="advice" class="advice.UserAdvice"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

3、使用注解定义其他 增强

//使用注解 配置异常抛出增强   参数是切入点,抛出的异常名
    @AfterThrowing(pointcut="myPointCut()",throwing="e")


//使用注解 配置最终增强   参数是切入点
    @After(value="myPointCut()")

//使用注解 配置AfterReturning增强   参数是切入点,返回结果变量名
    @AfterReturning(pointcut="myPointCut()",returning="result")


//使用注解 配置环绕增强   参数是切入点
    @Around(value="myPointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("调用" + pjp.getTarget().getClass().getName() + "的" +      pjp.getSignature().getName()+"方法入参:"+Arrays.toString(pjp.getArgs()));
        Object obj = null;
        try {
            // 让程序继续执行
            // 此处的obj不接收对afterreturning没有影响
            // 对程序中接受返回值有影响,所以要返回返回值
            obj = pjp.proceed();
            logger.debug(pjp.getTarget().getClass().getName() +"返回值是:" + obj);
            return obj;
        } catch (Throwable e) {
            logger.error(pjp.getTarget().getClass().getName() +"方法发生异常:"+e.getMessage());
            throw e;
        }
        finally{
            logger.info(pjp.getTarget().getClass().getName() +"方法结束");
        }

    }
相关标签: ape注解