Spring框架系列之AOP思想

2,826 阅读3分钟

微信公众号:compassblog

欢迎关注、转发,互相学习,共同进步!

有任何问题,请后台留言联系!

1、AOP概述

(1)、什么是 AOP

AOP 为 Aspect Oriented Programming 的缩写,意为“面向切面编程”。AOP 是 OOP (面向对象)的延续,可以对业务的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性和开发效率。

(2)、AOP 思想图解:横向重复,纵向切取

  • 过滤器


  • 拦截器


  • 事务管理


(3)、AOP 可以实现的功能

  • 权限验证

  • 日志记录

  • 性能控制

  • 事务控制

(4)、AOP 底层实现的两种代理机制

  • JDK的动态代理 :针对实现了接口的类产生代理

  • Cglib的动态代理 :针对没有实现接口的类产生代理,应用的是底层的字节码增强的技术生成当前类的子类对象

2、Spring底层AOP实现原理

(1)、 JDK 动态代理增强一个类中方法:被代理对象必须要实现接口,才能产生代理对象。如果没有接口将不能使用动态代理技术。

public class MyJDKProxy implements InvocationHandler { 

     private UserDao userDao; 

     public MyJDKProxy(UserDao userDao) {   
         this.userDao = userDao; 
     } 

    public UserDao createProxy(){
        UserDao  userDaoProxy  =  (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(), this);
        return userDaoProxy;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        if("save".equals(method.getName())){
            System.out.println("权限校验=============
        } 
        return method.invoke(userDao, args); 
    } 
} 

(2)、Cglib 动态代理增强一个类中的方法:可以对任何类生成代理,代理的原理是对目标对象进行继承代理。如果目标对象被final修饰,那么该类无法被cglib代理。

public class MyCglibProxy implements MethodInterceptor{ 

    private CustomerDao customerDao; 

    public MyCglibProxy(CustomerDao customerDao){   
        this.customerDao = customerDao; 
 } 

      // 生成代理的方法: 
    public CustomerDao createProxy(){ 
      // 创建Cglib的核心类: 
    Enhancer enhancer = new Enhancer(); 
      // 设置父类: 
      enhancer.setSuperclass(CustomerDao.class); 
      // 设置回调: 
      enhancer.setCallback(this); 
      // 生成代理: 
      CustomerDao customerDaoProxy = (CustomerDao) enhancer.create();   
      return customerDaoProxy; 
 } 

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    if("delete".equals(method.getName())){
        Object obj = methodProxy.invokeSuper(proxy, args);
        System.out.println("日志记录================");
        return obj;
        }
        return methodProxy.invokeSuper(proxy, args);
    }
}

3、Spring 基于 AspectJ AOP 开发的相关术语

  • Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点

  • Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义

  • Advice(通知/增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知,通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)

  • Introduction(引介):引介是一种特殊的通知,在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field

  • Target(目标对象):代理的目标对象

  • Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装在期织入

  • Proxy(代理):一个类被 AOP 织入增强后,就产生一个结果代理类

  • Aspect(切面):是切入点和通知(引介)的结合

您可能还喜欢:


本系列后期仍会持续更新,欢迎关注!


如果你认为这篇文章有用,欢迎转发分享给你的好友!

本号文章可以任意转载,转载请注明出处!


                             扫描关注微信公众号,了解更多