Spring核心之一:Aop

Spring 的关键组件之一是 AOP 框架。尽管 Spring IoC 容器不依赖于 AOP(这意味着您不需要使用 AOP),但 AOP 是对 Spring IoC 的补充,以提供功能非常强大的中间件解决方案。

Aop是面向切面编程:是一种横向编程的思想,在不影响原本类的情况下实现一些方法的增强

  • 切面(ASPECT):横切关注点 被模块化的特殊对象。是一个类
  • 通知(Advice):切面中需要完成的工作。即类中的方法
  • 目标(Target):被通知对象
  • 代理(Proxy):想目标对象应用通知之后创建的对象(动态代理)
  • 切入点(PointCut):切面通知 执行的“地点”的定义
  • 连接点(JointPoint):与切入点匹配的执行点

实现:

1.实现相应的切面接口(使用Spring API接口)

<!--注册bean-->
    <bean id="userService" class="service.UserServiceImpl"></bean>
    <bean id="beforeLog" class="log.BeforeLog"></bean>

<!--    配置aop-->
    <aop:config>
        <!--切入点  要从哪个位置切入-->
        <aop:pointcut id="poincut" expression="execution(* service.UserServiceImpl.*(..))"/>
    <!--  执行环绕增加: 将切面和切入点连接-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="poincut"></aop:advisor>
    </aop:config>
public class BeforeLog implements MethodBeforeAdvice {

    /**
     * 切面:相当于一个代理类
     * before:相当于invoke
     * @param method
     * @param args
     * @param target
     * @throws Throwable
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName());
        System.out.println(method.getName());
        System.out.println("前置通知");
    }
}

2.自定义类(自定义切面)

<!--    实现方式2:自定义切面-->
    <bean id="diyAspectj" class="自定义切面.DiyAspectj"></bean>
    <aop:config>
        <aop:aspect ref="diyAspectj">
            <!--切入点  要从哪个位置切入-->
            <aop:pointcut id="poincut" expression="execution(* service.UserServiceImpl.*(..))"/>
            <!-- 将切面和切入点连接-->
            <aop:before method="before" pointcut-ref="poincut"></aop:before>
            <aop:after-returning method="after" pointcut-ref="poincut"></aop:after-returning>
        </aop:aspect>
    </aop:config>
public class DiyAspectj {
    public void before(){
        System.out.println("前置通知");

    }
    public void after(){
        System.out.println("后置通知");
    }
}

3.使用注解实现

<!--    实现方式3-->
<!--    开启注解支持-->
    <bean id="annotationAspectj" class="AnnotationAspectj"></bean>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Aspect //该类是一个切面
public class AnnotationAspectj {

    @Before("execution(* service.UserServiceImpl.*(..))")
    void before(){
        System.out.println("注解--前置通知");
    }
    @Around("execution(* service.UserServiceImpl.*(..))")
    void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        jp.proceed();  //方法执行
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值