Java Dynamic Proxy And Aspect Application (一)

一 综述动态代理

1.术道之争

OPP

 面向过程(Procedure Oriented Programming)
 针对某一功能专门设计,独立完成上下文所有工序,尖兵性质,工作效率高
 比如:西红柿炒鸡蛋,一套完成;西红柿鸡蛋汤,又一套程序

OOP

面向对象(Object Oriented Programming)
针对系统设计,各个模块分工协作,以对象为单位,易于管理和能力复用
比如:西红柿处理、鸡蛋处理、调味料处理、厨具处理
组合产出:西红柿炒鸡蛋 或者 西红柿鸡蛋汤

AOP

面向切面(Aspect Oriented Programming)
针对系统某两个对象的工序之间插入一个切面方法,用于特殊处理,更加灵活
比如:在每次西红柿炒鸡蛋出锅前插入一个切面,判断是要甜口或咸口,并添加调料

2.综合理解

综合来看,面向过程设计的方法,每种实现都要完整设计;如果将方法内的通用部分抽象为一个对象,并将对象供其他方法调用,则系统将被简化,并且易于管理所抽象出的公共方法,从而使原来复杂的方法便于统一修改实现;多个对象又可以组合成更复杂的功能,通过切面,切入两个对象之间,对下游对象做增强,针对下游对象的某个方法做前置、环绕、后置处理,使系统功能更加复杂

在这里插入图片描述
无论是社会发展,工业生产,还是【软件开发】,一个系统的组成和完善,一定在内、外双驱动力下经历自我成长为稳定、合理、高效系统的过程。世间万物基于真理的潜在关联都是相通的。

二 Java 动态代理

如果AOP是道,动态代理就是术,即通过一定编码规则使AOP的切面自动织入系统,而不需要人为去做编写增强方法的适配。Java 内有两种方法实现:JDK动态代理、CGLIB动态代理

1.JDK & CGLIB

项目JDKCGLIB
手段反射机制字节码处理框架ASM
效率生成高,执行低生成低,执行高
限制委托机制,仅针对接口类继承机制,非Final修饰的类
实现1.实现InvocationHandler接口,重写invoke()
2.使用Proxy.newProxyInstance()产生代理对象
3.被代理的对象必须要实现接口
1.依赖于CGLib的类库
2.实现MethodInterceptor接口,重写intercept()
3.使用Enhancer对象.create()产生代理对象

2.选型

如果类实现了接口,则可以使用JDK自带的动态代理,否则只能使用基于ASM的CGLIB,注意类如果被Final修饰则无法继承,则无法使用CGLIB;Springboot默认优先使用JDK的,如果不满足条件会自动切换CGLIB

三 测试

1.JDK动态代理

1.反射简述

双亲委派模型保证了Jvm加载Class对象的唯一性,通过Java Reflection API可以拿到任何一个已知名称的类   
的内部信息,如Fields(属性)、Method(方法)、Constrous(构造)
反射机制允许我们动态的调用某个对象的方法/构造函数、获取某个对象的属性等,而无需在编码时确定调用的对象

定义一个兔子类

package com.demo.reflect;

/**
 * @author 
 * @date 2022-10-02 18:25
 * @since 1.8
 */
public class Rabbit {

    /**
     * 标准重量 KG
     */
    private final int STANDARD_WEIGHT_KG = 10;

    /**
     * 体重
     */
    private int weight;

    /**
     * 无参初始重量
     */
    public Rabbit(){
        this.weight = 0;
    }

    /**
     * 有参初始重量
     * @param weight
     */
    public Rabbit(int weight){
        this.weight = weight;
    }

    /**
     * 是否超重
     * @return
     */
    public boolean isOverWeight(){
        if (weight > STANDARD_WEIGHT_KG){
            return true;
        }
        return false;
    }
}

反射测试

package com.demo.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 
 * @date 2022-10-02 18:23
 * @since 1.8
 */
public class ReflectRabbit {

    /**
     * 获取方法方法:私有方法需要修改权限后获取
     * method.setAccessible(true);
     * @param args
     */
    public static void main(String[] args) {
        try {
            //获取Class对象
            Class classObj = Class.forName("com.demo.reflect.Rabbit");
            //创建无参实例
            Object rabbitOne = classObj.newInstance();
            //创建有参实例
            Constructor constructor = classObj.getConstructor(int.class);
            Object rabbitTwo = constructor.newInstance(11);
            //获取方法
            Method method = classObj.getDeclaredMethod("isOverWeight",null);
            //调用
            System.out.println(method.invoke(rabbitOne,null));
            System.out.println(method.invoke(rabbitTwo,null));

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

效果

在这里插入图片描述

2.动态代理

工程结构

在这里插入图片描述
喂养接口类

package com.demo.service;

/**
 * @author
 * @date 2022-10-02 13:47
 * @since 1.8
 */
public interface FeedInterface {
    /**
     * 喂养
     */
    void feed();
}

洗澡接口类

package com.demo.service;

/**
 * @author
 * @date 2022-10-02 17:25
 * @since 1.8
 */
public interface WashInterface {

    /**
     * 洗
     */
    void wash();
}

实现类

package com.demo.service.impl;

import com.demo.service.FeedInterface;
import com.demo.service.WashInterface;

/**
 * @author
 * @date 2022-10-02 13:47
 * @since 1.8
 */
public class FeedRabbitImpl implements FeedInterface, WashInterface {

    @Override
    public void feed() {
        System.out.println("喂养兔子");
    }

    @Override
    public void wash() {
        System.out.println("洗兔子");
    }
}

代理类

package com.demo.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhanghx19
 * @date 2022-10-02 12:00
 * @since 1.8
 */
public class JdkProxy implements InvocationHandler {

    /**
     * 被代理对象(原始对象)
     */
    private Object target;

    /**
     * 初始化被代理对象
     * @param target
     */
    public JdkProxy(Object target){
        this.target = target;
    }

    /**
     * 获取代理对象(新生成的对象)
     * @return
     */
    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }

    /**
     * 重写 Invoke 方法
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //增强处理
        switch (method.getName()){
            case "feed":
                System.out.println("准备青草...");
                break;
            case "wash":
                System.out.println("准备清水...");
                break;
            default:
                System.out.println("Others");
                break;
        }
        //
        Object result = method.invoke(target,args);
        return result;
    }
}

测试

package com.demo;

import com.demo.proxy.jdk.JdkProxy;
import com.demo.service.FeedInterface;
import com.demo.service.WashInterface;
import com.demo.service.impl.FeedRabbitImpl;

/**
 * @author
 * @date 2022-10-02 13:57
 * @since 1.8
 */
public class TestProxy {


    public static void main(String[] args) {

        /**
         * 被代理
         */
        FeedRabbitImpl target = new FeedRabbitImpl();

        /**
         * 代理实现
         */
        JdkProxy jdkProxy = new JdkProxy(target);

        /**
         * 代理对象
         */
        Object proxy = jdkProxy.getProxy();

        ((FeedInterface)proxy).feed();

        ((WashInterface)proxy).wash();

    }
}

效果

在这里插入图片描述

3.源码简析(可忽略,仅记录了一下源码大概调用顺序)

生成代理类的源码

/**
 * Returns an instance of a proxy class for the specified interfaces
 * that dispatches method invocations to the specified invocation
 * handler.
 *
 * <p>{@code Proxy.newProxyInstance} throws
 * {@code IllegalArgumentException} for the same reasons that
 * {@code Proxy.getProxyClass} does.
 *
 * @param   loader the class loader to define the proxy class
 * @param   interfaces the list of interfaces for the proxy class
 *          to implement
 * @param   h the invocation handler to dispatch method invocations to
 * @return  a proxy instance with the specified invocation handler of a
 *          proxy class that is defined by the specified class loader
 *          and that implements the specified interfaces
 * @throws  IllegalArgumentException if any of the restrictions on the
 *          parameters that may be passed to {@code getProxyClass}
 *          are violated
 * @throws  SecurityException if a security manager, <em>s</em>, is present
 *          and any of the following conditions is met:
 *          <ul>
 *          <li> the given {@code loader} is {@code null} and
 *               the caller's class loader is not {@code null} and the
 *               invocation of {@link SecurityManager#checkPermission
 *               s.checkPermission} with
 *               {@code RuntimePermission("getClassLoader")} permission
 *               denies access;</li>
 *          <li> for each proxy interface, {@code intf},
 *               the caller's class loader is not the same as or an
 *               ancestor of the class loader for {@code intf} and
 *               invocation of {@link SecurityManager#checkPackageAccess
 *               s.checkPackageAccess()} denies access to {@code intf};</li>
 *          <li> any of the given proxy interfaces is non-public and the
 *               caller class is not in the same {@linkplain Package runtime package}
 *               as the non-public interface and the invocation of
 *               {@link SecurityManager#checkPermission s.checkPermission} with
 *               {@code ReflectPermission("newProxyInPackage.{package name}")}
 *               permission denies access.</li>
 *          </ul>
 * @throws  NullPointerException if the {@code interfaces} array
 *          argument or any of its elements are {@code null}, or
 *          if the invocation handler, {@code h}, is
 *          {@code null}
 */
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)
    throws IllegalArgumentException
{
    Objects.requireNonNull(h);

    final Class<?>[] intfs = interfaces.clone();
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
    }

    /*
     * Look up or generate the designated proxy class.
     */
    Class<?> cl = getProxyClass0(loader, intfs);

    /*
     * Invoke its constructor with the designated invocation handler.
     */
    try {
        if (sm != null) {
            checkNewProxyPermission(Reflection.getCallerClass(), cl);
        }

        final Constructor<?> cons = cl.getConstructor(constructorParams);
        final InvocationHandler ih = h;
        if (!Modifier.isPublic(cl.getModifiers())) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    cons.setAccessible(true);
                    return null;
                }
            });
        }
        return cons.newInstance(new Object[]{h});
    } catch (IllegalAccessException|InstantiationException e) {
        throw new InternalError(e.toString(), e);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new InternalError(t.toString(), t);
        }
    } catch (NoSuchMethodException e) {
        throw new InternalError(e.toString(), e);
    }
}

关键在查找或生成代理类:Class<?> cl = getProxyClass0(loader, intfs)

/**
 * Generate a proxy class.  Must call the checkProxyAccess method
 * to perform permission checks before calling this.
 */
private static Class<?> getProxyClass0(ClassLoader loader,
                                       Class<?>... interfaces) {
    if (interfaces.length > 65535) {
        throw new IllegalArgumentException("interface limit exceeded");
    }

    // If the proxy class defined by the given loader implementing
    // the given interfaces exists, this will simply return the cached copy;
    // otherwise, it will create the proxy class via the ProxyClassFactory
    return proxyClassCache.get(loader, interfaces);
}

从缓存查找,不存在就创建并添加到缓存

/**
 * Look-up the value through the cache. This always evaluates the
 * {@code subKeyFactory} function and optionally evaluates
 * {@code valueFactory} function if there is no entry in the cache for given
 * pair of (key, subKey) or the entry has already been cleared.
 *
 * @param key       possibly null key
 * @param parameter parameter used together with key to create sub-key and
 *                  value (should not be null)
 * @return the cached value (never null)
 * @throws NullPointerException if {@code parameter} passed in or
 *                              {@code sub-key} calculated by
 *                              {@code subKeyFactory} or {@code value}
 *                              calculated by {@code valueFactory} is null.
 */
 public V get(K key, P parameter) {
     Objects.requireNonNull(parameter);

     expungeStaleEntries();

     Object cacheKey = CacheKey.valueOf(key, refQueue);

     // lazily install the 2nd level valuesMap for the particular cacheKey
     ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
     if (valuesMap == null) {
         ConcurrentMap<Object, Supplier<V>> oldValuesMap
             = map.putIfAbsent(cacheKey,
                               valuesMap = new ConcurrentHashMap<>());
         if (oldValuesMap != null) {
             valuesMap = oldValuesMap;
         }
     }

     // create subKey and retrieve the possible Supplier<V> stored by that
     // subKey from valuesMap
     Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
     Supplier<V> supplier = valuesMap.get(subKey);
     Factory factory = null;

     while (true) {
         if (supplier != null) {
             // supplier might be a Factory or a CacheValue<V> instance
             V value = supplier.get();
             if (value != null) {
                 return value;
             }
         }
         // else no supplier in cache
         // or a supplier that returned null (could be a cleared CacheValue
         // or a Factory that wasn't successful in installing the CacheValue)

         // lazily construct a Factory
         if (factory == null) {
             factory = new Factory(key, parameter, subKey, valuesMap);
         }

         if (supplier == null) {
             supplier = valuesMap.putIfAbsent(subKey, factory);
             if (supplier == null) {
                 // successfully installed Factory
                 supplier = factory;
             }
             // else retry with winning supplier
         } else {
             if (valuesMap.replace(subKey, supplier, factory)) {
                 // successfully replaced
                 // cleared CacheEntry / unsuccessful Factory
                 // with our Factory
                 supplier = factory;
             } else {
                 // retry with current supplier
                 supplier = valuesMap.get(subKey);
             }
         }
     }
 }

supplier.get() 即 Factory:factory.get()

@Override
public synchronized V get() { // serialize access
    // re-check
    Supplier<V> supplier = valuesMap.get(subKey);
    if (supplier != this) {
        // something changed while we were waiting:
        // might be that we were replaced by a CacheValue
        // or were removed because of failure ->
        // return null to signal WeakCache.get() to retry
        // the loop
        return null;
    }
    // else still us (supplier == this)

    // create new value
    V value = null;
    try {
        value = Objects.requireNonNull(valueFactory.apply(key, parameter));
    } finally {
        if (value == null) { // remove us on failure
            valuesMap.remove(subKey, this);
        }
    }
    // the only path to reach here is with non-null value
    assert value != null;

    // wrap value with CacheValue (WeakReference)
    CacheValue<V> cacheValue = new CacheValue<>(value);

    // put into reverseMap
    reverseMap.put(cacheValue, Boolean.TRUE);

    // try replacing us with CacheValue (this should always succeed)
    if (!valuesMap.replace(subKey, this, cacheValue)) {
        throw new AssertionError("Should not reach here");
    }

    // successfully replaced us with new CacheValue -> return the value
    // wrapped by it
    return value;
}

由 private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
可知factory类型为:ProxyClassFactory
查看 Proxy:ProxyClassFactory:apply()

@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

    Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
    for (Class<?> intf : interfaces) {
        /*
         * Verify that the class loader resolves the name of this
         * interface to the same Class object.
         */
        Class<?> interfaceClass = null;
        try {
            interfaceClass = Class.forName(intf.getName(), false, loader);
        } catch (ClassNotFoundException e) {
        }
        if (interfaceClass != intf) {
            throw new IllegalArgumentException(
                intf + " is not visible from class loader");
        }
        /*
         * Verify that the Class object actually represents an
         * interface.
         */
        if (!interfaceClass.isInterface()) {
            throw new IllegalArgumentException(
                interfaceClass.getName() + " is not an interface");
        }
        /*
         * Verify that this interface is not a duplicate.
         */
        if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
            throw new IllegalArgumentException(
                "repeated interface: " + interfaceClass.getName());
        }
    }

    String proxyPkg = null;     // package to define proxy class in
    int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

    /*
     * Record the package of a non-public proxy interface so that the
     * proxy class will be defined in the same package.  Verify that
     * all non-public proxy interfaces are in the same package.
     */
    for (Class<?> intf : interfaces) {
        int flags = intf.getModifiers();
        if (!Modifier.isPublic(flags)) {
            accessFlags = Modifier.FINAL;
            String name = intf.getName();
            int n = name.lastIndexOf('.');
            String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
            if (proxyPkg == null) {
                proxyPkg = pkg;
            } else if (!pkg.equals(proxyPkg)) {
                throw new IllegalArgumentException(
                    "non-public interfaces from different packages");
            }
        }
    }

    if (proxyPkg == null) {
        // if no non-public proxy interfaces, use com.sun.proxy package
        proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
    }

    /*
     * Choose a name for the proxy class to generate.
     */
    long num = nextUniqueNumber.getAndIncrement();
    String proxyName = proxyPkg + proxyClassNamePrefix + num;

    /*
     * Generate the specified proxy class.
     */
    byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
        proxyName, interfaces, accessFlags);
    try {
        return defineClass0(loader, proxyName,
                            proxyClassFile, 0, proxyClassFile.length);
    } catch (ClassFormatError e) {
        /*
         * A ClassFormatError here means that (barring bugs in the
         * proxy class generation code) there was some other
         * invalid aspect of the arguments supplied to the proxy
         * class creation (such as virtual machine limitations
         * exceeded).
         */
        throw new IllegalArgumentException(e.toString());
    }
}

生成:ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)

2.CGLIB动态代理

1.依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>proxy</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--配置为阿里云-->
    <repositories>
        <repository>
            <id>aliyun</id>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>

</project>

2.动态代理

定义兔子类

package com.demo.proxy.cglib;

/**
 * @author
 * @date 2022-10-02 20:34
 * @since 1.8
 */
public class Rabbit {

    /**
     * 训练兔子
     */
    public void train(){
        System.out.println("训练兔子...");
    }
}

定义代理了类

package com.demo.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author
 * @date 2022-10-02 20:29
 * @since 1.8
 */
public class CglibProxy implements MethodInterceptor {

    /**
     * 被代理对象
     */
    private Object target;

    /**
     * 初始化被代理对象
     * @param target
     */
    public CglibProxy(Object target){
        this.target = target;
    }

    /**
     * 获取被代理对象
     * @return
     */
    public <T> T getProxyInstance(Class clazz){

        //工具类
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target.getClass());
        //设置回调函数
        enhancer.setCallback(this);
        //创建对象
        return (T) enhancer.create();
    }

    /**
     *
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("准备场地和胡萝卜...");
        Object result = methodProxy.invokeSuper(o,objects);
        System.out.println("打扫场地...");
        return result;
    }
}

测试类

package com.demo;

import com.demo.proxy.cglib.CglibProxy;
import com.demo.proxy.cglib.Rabbit;
import com.demo.proxy.jdk.JdkProxy;

/**
 * @author
 * @date 2022-10-02 13:57
 * @since 1.8
 */
public class TestProxy {


    public static void main(String[] args) {

        Rabbit target = new Rabbit();

        CglibProxy cglibProxy = new CglibProxy(target);

        Rabbit proxy = cglibProxy.getProxyInstance(Rabbit.class);

        proxy.train();

    }
}

效果

在这里插入图片描述

3.简析

JDK 代理是调用被代理类对象执行原来方法:method.invoke(target,args)
CGLIB 代理是调用父类方法执行原理方法:methodProxy.invokeSuper