三分钟看完Spring实现AOP的三种方法

方法一:使用原声spring API接口

创建一个类去继承

 before增强方法继承MethodBeforeAdvice类,实现抽象方法。

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

after增强方法继承AfterReturningAdvice类,实现抽象方法

public class AfterLog implements AfterReturningAdvice {

    //returnValue;返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为"+returnValue);
    }
}

XML定义切入点,使增强方法作用于切入点

<!--配置aop:需要导入aop的约束-->
    <aop:config>
    <!--切入点:experssion:表达式,execution(要执行的位置!*****)-->
        <aop:pointcut id="pointcut" expression="execution(* com.LL.sp7.*.*(..))"/>
        <!--执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
     </aop:config>

方法二:自定义类实现增强

自定义增强类

public class DiyPointCut {
    public void before(){
        System.out.println("======方法执行前======");
    }

    public void after(){
        System.out.println("======方法执行后======");

    }
}

XML定义切点,定义增强方法

<aop:config>
        <!--自定义切面,ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.LL.sp7.UserService.*(..))"/>
            <!--通知-->
            <!--设置在切入点之前-->
            <aop:before method="before" pointcut-ref="point"/>
            <!--设置在切入点之后-->
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方法三:注解

直接在增强方法上定义切入点

@Aspect     //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.LL.sp7.UserService.*(..))")
    public void before(){
        System.out.println("======方法执行之前==========");
    }
}

XML开启注解支持

 <!--开启注解支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy proxy-target-class="false" />
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狗头实习生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值