小工具知识网

当前位置: 首页 > 行业知识 > Java-springboot动态加载jar包,动态配置

行业知识

Java-springboot动态加载jar包,动态配置

2026-12-06 00:17:34 来源:互联网转载

一、概述

1、背景

​ 目前数据治理服务中有众多治理任务,当其中任一治理任务有改动需要升级或新增一个治理任务时,都需要将数据治理服务重启,会影响其他治理任务的正常运行。

()

2、目标

  1. 能够动态启动、停止任一治理任务
  2. 能够动态升级、添加治理任务
  3. 启动、停止治理任务或升级、添加治理任务不能影响其他任务

3、方案

  1. 为了支持业务代码尽量的解耦,把部分业务功能通过动态加载的方式加载到主程序中,以满足可插拔式的加载、组合式的部署。
  2. 配合xxl-job任务调度框架,将数据治理任务做成xxl-job任务的方式注册到xxl-job中,方便统一管理。

二、动态加载

1、自定义类加载器

URLClassLoader 是一种特殊的类加载器,可以从指定的 URL 中加载类和资源。它的主要作用是动态加载外部的 JAR 包或者类文件,从而实现动态扩展应用程序的功。为了便于管理动态加载的jar包,自定义类加载器继承URLClassloader。

package cn.jy.sjzl.util;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * 自定义类加载器 * * @author lijianyu * @date 2023/04/03 17:54 **/public class MyClassLoader extends URLClassLoader {    private Map> getLoadedClasses() {        return loadedClasses;    }    public MyClassLoader(URL[] urls, ClassLoader parent) {        super(urls, parent);    }    @Override    protected Class findClass(String name) throws ClassNotFoundException {        // 从已加载的类集合中获取指定名称的类        Class clazz = loadedClasses.get(name);        if (clazz != null) {            return clazz;        }        try {            // 调用父类的findClass方法加载指定名称的类            clazz = super.findClass(name);            // 将加载的类添加到已加载的类集合中            loadedClasses.put(name, clazz);            return clazz;        } catch (ClassNotFoundException e) {            e.printStackTrace();            return null;        }    }    public void unload() {        try {            for (Map.Entry> entry : loadedClasses.entrySet()){                String className = entry.getKey();                Class clazz = entry.getValue();                // 2. 将有@spring注解的类交给spring管理                // 2.1 判断是否注入spring                Boolean flag = SpringAnnotationUtils.hasSpringAnnotation(clazz);                if(flag){                    // 2.2交给spring管理                    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);                    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();                    // 此处beanName使用全路径名是为了防止beanName重复                    String packageName = className.substring(0, className.lastIndexOf(".") + 1);                    String beanName = className.substring(className.lastIndexOf(".") + 1);                    beanName = packageName + beanName.substring(0, 1).toLowerCase() + beanName.substring(1);                    // 2.3注册到spring的beanFactory中                    beanFactory.registerBeanDefinition(beanName, beanDefinition);                    // 2.4允许注入和反向注入                    beanFactory.autowireBean(clazz);                    beanFactory.initializeBean(clazz, beanName);                    /*if(Arrays.stream(clazz.getInterfaces()).collect(Collectors.toSet()).contains(InitializingBean.class)){                        initBeanClass.add(clazz);                    }*/                    initBeanClass.add(clazz);                }                // 3. 带有XxlJob注解的方法注册任务                // 3.1 过滤方法                Map annotatedMethods = null;                try {                    annotatedMethods = MethodIntrospector.selectMethods(clazz,                            new MethodIntrospector.MetadataLookup() {                                @Override                                public XxlJob inspect(Method method) {                                    return AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class);                                }                            });                } catch (Throwable ex) {                }                // 3.2 生成并注册方法的JobHander                for (Map.Entry methodXxlJobEntry : annotatedMethods.entrySet()) {                    Method executeMethod = methodXxlJobEntry.getKey();                    // 获取jobHander和Cron                    XxlJobCron xxlJobCron = executeMethod.getAnnotation(XxlJobCron.class);                    if(xxlJobCron == null){                        throw new CustomException("500", executeMethod.getName() + "(),没有添加@XxlJobCron注解配置定时策略");                    }                    if (!CronExpression.isValidExpression(xxlJobCron.value())) {                        throw new CustomException("500", executeMethod.getName() + "(),@XxlJobCron参数内容错误");                    }                    XxlJob xxlJob = methodXxlJobEntry.getValue();                    jobPar.put(xxlJob.value(), xxlJobCron.value());                    if (isRegistXxlJob) {                        executeMethod.setAccessible(true);                        // regist                        Method initMethod = null;                        Method destroyMethod = null;                        xxlJobExecutor.registJobHandler(xxlJob.value(), new CustomerMethodJobHandler(clazz, executeMethod, initMethod, destroyMethod));                    }                }            }            // spring bean实际注册            initBeanClass.forEach(beanFactory::getBean);        } catch (IOException e) {            logger.error("读取{} 文件异常", fileName);            e.printStackTrace();            throw new RuntimeException("读取jar文件异常: " + fileName);        }    }}

以下是判断该类是否有spring注解的工具类

apublic class SpringAnnotationUtils {    private static Logger logger = LoggerFactory.getLogger(SpringAnnotationUtils.class);    /**     * 判断一个类是否有 Spring 核心注解     *     * @param clazz 要检查的类     * @return true 如果该类上添加了相应的 Spring 注解;否则返回 false     */    public static boolean hasSpringAnnotation(Class clazz) {        if (clazz == null) {            return false;        }        //是否是接口        if (clazz.isInterface()) {            return false;        }        //是否是抽象类        if (Modifier.isAbstract(clazz.getModifiers())) {            return false;        }        try {            if (clazz.getAnnotation(Component.class) != null ||            clazz.getAnnotation(Repository.class) != null ||            clazz.getAnnotation(Service.class) != null ||            clazz.getAnnotation(Controller.class) != null ||            clazz.getAnnotation(Configuration.class) != null) {                return true;            }        }catch (Exception e){            logger.error("出现异常:{}",e.getMessage());        }        return false;    }}

注册xxljob执行器的操作是仿照的xxljob中的XxlJobSpringExecutor的注册方法。

3、动态卸载

动态卸载的过程,就是将动态加载的代码,从内存,spring以及xxljob中移除。

代码如下:

    /**     * 动态卸载指定路径下指定jar包     * @param fileName     * @return map 创建xxljob任务时需要的参数配置     */    public void unloadJar(String fileName) throws IllegalAccessException, NoSuchFieldException {        // 获取加载当前jar的类加载器        MyClassLoader myClassLoader = myClassLoaderCenter.get(fileName);        // 获取jobHandlerRepository私有属性,为了卸载xxljob任务        Field privateField = XxlJobExecutor.class.getDeclaredField("jobHandlerRepository");        // 设置私有属性可访问        privateField.setAccessible(true);        // 获取私有属性的值jobHandlerRepository        XxlJobExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();        Map jobHandlerRepository = (ConcurrentHashMap) privateField.get(xxlJobSpringExecutor);        // 获取beanFactory,准备从spring中卸载        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();        Map> classes = (Vector

上一篇:我的世界iOS下载教程

下一篇:怎么在服务器中刷物品的?