How does Spring Boot hot load jar to implement dynamic plug-ins?Spring Boot 如何热加载 jar 实现动态插件?

1. Background

Dynamic plug-in programming is a cool thing. The decoupling that can realize business functions is easy to maintain, and it can also improve the can be extended without stopping the server at any time, and it is also very good Openness can not only develop functions by its own R&D staff, but also accept plug-ins developed by third-party developers in accordance with specifications.

Common implementations of dynamic plug-ins include SPI , OSGI etc. Because it is separated from the management of Spring IOC, the Bean object of the main program cannot be injected into the plug-in. For example, the main program has integrated Redis but cannot be used in the plug-in.

This article mainly introduces an implementation idea of hot loading jar packages in Spring Boot projects and registering them as Bean objects. While dynamically expanding functions, it supports injecting the beans of the main program into plug-ins to achieve more powerful plug-ins.

 

Two, hot load jar package

Loading a specified dynamic link or path through the jar package, may be used URLClassLoader the addURL way to implement, the sample code is as follows:

ClassLoaderUtil Class

public class ClassLoaderUtil {
    public static ClassLoader getClassLoader(String url) {
        try {
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            URLClassLoader classLoader = new URLClassLoader(new URL[]{}, ClassLoader.getSystemClassLoader());
            method.invoke(classLoader, new URL(url));
            return classLoader;
        } catch (Exception e) {
            log.error("getClassLoader-error", e);
            return null;
        }
    }
}

When creating URLClassLoader , it is critical to specify the ClassLoader of the current system as the parent class loader ClassLoader.getSystemClassLoader() which is used to open up the ClassLoader between the main program and the plug-in, and solve various ClassNotFoundException problems when the plug-in is registered into the IOC.

 

Three, dynamically register Bean

Register the implementation class loaded in the plug-in jar into Spring's IOC, and at the same time inject the existing Beans in the IOC into the plug-in; the implementation methods are respectively in the two scenarios of program startup and runtime.

3.1. Register Bean at startup

Use ImportBeanDefinitionRegistrar to dynamically register the Bean of the plug-in when Spring Boot starts. The sample code is as follows:

PluginImportBeanDefinitionRegistrar class

public class PluginImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    private final String targetUrl = "file:/D:/SpringBootPluginTest/plugins/plugin-impl-0.0.1-SNAPSHOT.jar";
    private final String pluginClass = "com.plugin.impl.PluginImpl";

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ClassLoader classLoader = ClassLoaderUtil.getClassLoader(targetUrl);
        Class<?> clazz = classLoader.loadClass(pluginClass);
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        BeanDefinition beanDefinition = builder.getBeanDefinition();
        registry.registerBeanDefinition(clazz.getName(), beanDefinition);
    }
}

 

3.2. Registering Beans at runtime

The Bean of the plug-in dynamically registered when the program is running is ApplicationContext object. The sample code is as follows:

@GetMapping("/reload")
public Object reload() throws ClassNotFoundException {
        ClassLoader classLoader = ClassLoaderUtil.getClassLoader(targetUrl);
        Class<?> clazz = classLoader.loadClass(pluginClass);
        springUtil.registerBean(clazz.getName(), clazz);
        PluginInterface plugin = (PluginInterface)springUtil.getBean(clazz.getName());
        return plugin.sayHello("test reload");
}

SpringUtil class

@Component
public class SpringUtil implements ApplicationContextAware {
    private DefaultListableBeanFactory defaultListableBeanFactory;
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        this.defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    }

    public void registerBean(String beanName, Class<?> clazz) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
    }

    public Object getBean(String name) {
        return applicationContext.getBean(name);
    }
}

 

Four, summary

The plug-in implementation ideas introduced in this article use share ClassLoader and dynamically register Bean , which opens up the class loader and Spring container between the plug-in and the main program, making it very convenient to implement plug-ins and plug-ins. type interaction with the main program , such as injecting Redis and DataSource of the main program into the plug-in, calling the remote Dubbo interface, etc.

However, because there is no alignment between the plug ClassLoader be isolation may also exist problems such as class conflict, version conflicts; and because of ClassLoader Class object can not be destroyed, so unless you change the class name or class path, or plug-in is loaded The class to the ClassLoader cannot be modified dynamically.

Therefore, this solution is more suitable for scenarios where the amount of plug-in data is not too much, the plug-in has good development specifications, and the plug-in can be launched or released after being tested.

 

Five, complete demo

https://github.com/zlt2000/springs-boot-plugin-test

一、背景

动态插件化编程是一件很酷的事情,能实现业务功能的 「解耦」 便于维护,另外也可以提升 「可扩展性」 随时可以在不停服务器的情况下扩展功能,也具有非常好的 「开放性」 除了自己的研发人员可以开发功能之外,也能接纳第三方开发商按照规范开发的插件。

常见的动态插件的实现方式有 SPIOSGI 等方案,由于脱离了 Spring IOC 的管理在插件中无法注入主程序的 Bean 对象,例如主程序中已经集成了 Redis 但是在插件中无法使用。

本文主要介绍在 Spring Boot 工程中热加载 jar 包并注册成为 Bean 对象的一种实现思路,在动态扩展功能的同时支持在插件中注入主程序的 Bean 实现功能更强大的插件。

 

二、热加载 jar 包

通过指定的链接或者路径动态加载 jar 包,可以使用 URLClassLoader 的 addURL 方法来实现,样例代码如下:

「ClassLoaderUtil 类」

public class ClassLoaderUtil {
    public static ClassLoader getClassLoader(String url) {
        try {
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            URLClassLoader classLoader = new URLClassLoader(new URL[]{}, ClassLoader.getSystemClassLoader());
            method.invoke(classLoader, new URL(url));
            return classLoader;
        } catch (Exception e) {
            log.error("getClassLoader-error", e);
            return null;
        }
    }
}

其中在创建 URLClassLoader 时,指定当前系统的 ClassLoader 为父类加载器  ClassLoader.getSystemClassLoader() 这步比较关键,用于打通主程序与插件之间的 ClassLoader ,解决把插件注册进 IOC 时的各种 ClassNotFoundException 问题。

 

三、动态注册 Bean

将插件 jar 中加载的实现类注册到 Spring 的 IOC 中,同时也会将 IOC 中已有的 Bean 注入进插件中;分别在程序启动时和运行时两种场景下的实现方式。

3.1. 启动时注册

使用 ImportBeanDefinitionRegistrar  实现在 Spring Boot 启动时动态注册插件的 Bean,样例代码如下:「PluginImportBeanDefinitionRegistrar 类」

public class PluginImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    private final String targetUrl = "file:/D:/SpringBootPluginTest/plugins/plugin-impl-0.0.1-SNAPSHOT.jar";
    private final String pluginClass = "com.plugin.impl.PluginImpl";

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ClassLoader classLoader = ClassLoaderUtil.getClassLoader(targetUrl);
        Class<?> clazz = classLoader.loadClass(pluginClass);
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        BeanDefinition beanDefinition = builder.getBeanDefinition();
        registry.registerBeanDefinition(clazz.getName(), beanDefinition);
    }
}

 

3.2. 运行时注册

程序运行时动态注册插件的 Bean 通过使用 ApplicationContext 对象来实现,样例代码如下:

@GetMapping("/reload")
public Object reload() throws ClassNotFoundException {
  ClassLoader classLoader = ClassLoaderUtil.getClassLoader(targetUrl);
  Class<?> clazz = classLoader.loadClass(pluginClass);
  springUtil.registerBean(clazz.getName(), clazz);
  PluginInterface plugin = (PluginInterface)springUtil.getBean(clazz.getName());
  return plugin.sayHello("test reload");
}

「SpringUtil 类」

@Component
public class SpringUtil implements ApplicationContextAware {
    private DefaultListableBeanFactory defaultListableBeanFactory;
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        this.defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    }

    public void registerBean(String beanName, Class<?> clazz) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
    }

    public Object getBean(String name) {
        return applicationContext.getBean(name);
    }
}

 

四、总结

本文介绍的插件化实现思路通过 「共用 ClassLoader」 和 「动态注册 Bean」 的方式,打通了插件与主程序之间的类加载器和 Spring 容器,使得可以非常方便的实现插件与插件之间和插件与主程序之间的 「类交互」,例如在插件中注入主程序的 Redis、DataSource、调用远程 Dubbo 接口等等。

但是由于没有对插件之间的 ClassLoader 进行 「隔离」 也可能会存在如类冲突、版本冲突等问题;并且由于 ClassLoader 中的 Class 对象无法销毁,所以除非修改类名或者类路径,不然插件中已加载到 ClassLoader 的类是没办法动态修改的。

所以本方案比较适合插件数据量不会太多、具有较好的开发规范、插件经过测试后才能上线或发布的场景。

 

五、完整 demo

https://github.com/zlt2000/springs-boot-plugin-test

posted @ 2024-07-02 10:22  CharyGao  阅读(63)  评论(0)    收藏  举报