SpringBoot项目动态加载jar 实战级别

网上也找到类似的文章,但是基本都不到实用级别,就是不能直接用。在参照网上的文章及与AI沟通N次后终于完善可以在实际项目上

  1. 创建jar文件动态加载类
java 复制代码
@Component
@Slf4j
public class PluginRegistry {

    @Autowired
    private GenericApplicationContext applicationContext;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    private final Map<String, URLClassLoader> loaders = new ConcurrentHashMap<>();

    public void loadPlugin(String jarPath) throws Exception {
        // 将 JAR 文件转换为 URL
        File jarFile = new File(jarPath);
        if (!jarFile.exists()) {
            throw new IllegalArgumentException("JAR file not found: " + jarPath);
        }
        URL jarUrl = jarFile.toURI().toURL();
        URLClassLoader classLoader = new URLClassLoader(
                new URL[]{jarUrl},
                Thread.currentThread().getContextClassLoader()
        );
        Thread.currentThread().setContextClassLoader(classLoader);

        ClassPathScanningCandidateComponentProvider scanner =
                new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));

        Set<BeanDefinition> candidateComponents =
                scanner.findCandidateComponents("com.snail.model"); // 替换为目标包路径

        // 注册扫描到的 Controller 到 Spring 容器
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory();
        for (org.springframework.beans.factory.config.BeanDefinition bd : candidateComponents) {
            String className = bd.getBeanClassName();
            Class<?> clazz = classLoader.loadClass(className);
            applicationContext.registerBean(clazz);
        }
        requestMappingHandlerMapping.afterPropertiesSet();
        log.info("加载插件成功{}",requestMappingHandlerMapping.getHandlerMethods().size());
        loaders.put(jarPath, classLoader);
    }
}

加载jar包,并扫描Commpent 注解,并注册到spring容器中,同时更新RequestMappingHandler(这样Controller就能生效了) 。 --- 应该还需要实现spring boot 的SPI 等,以支持更多场景。

  1. 发布动态加载jar文件的接口
    这个简单 就是创建一个controller 来调用动态加载的方法。
  2. 准备测试jar
    随意创建一个springmvc的项目并打包成jar文件即可。
  3. 测试结果
    启动主程序,通过接口将测试的jar加载进来,在访问新加载进来的接口测试
相关推荐
学长毕设4 小时前
基于SpringBoot的野生动物公益保护平台设计与实现-附源码
java·spring boot·后端
梦里寻码5 小时前
我用 NestJS + Vue3 写了一套完整的研发管理系统(58 表 / 229 API / 130 项断言,全开源
前端·后端·算法
鶴哥只手遮天5 小时前
《Redis 8.10.3 深度剖析》系列 ·第 10 章 Hash 一:`listpack`、`hashtable` 与 `LISTPACK_EX`
redis·后端·开源
johnjincaaaa5 小时前
WebAssembly 逆向实战:从 0 搞懂猿人学第 15 题
后端
Gopher_HBo5 小时前
Go CPU 剖析:四角色白话机制 + 实测实验
后端
猿人谷5 小时前
Surrogate Model:让进化算法学会“预测”,为什么它正在成为智能优化的重要技术?
后端·算法·架构
她的男孩5 小时前
三人会签只批了一个就往下走:Forge Admin 把 all / any / ratio 写成 completionCondition
spring boot·低代码·工作流引擎
the局外人6 小时前
LangChain ToolRuntime 入门:context、state 与 store 的实际用法
后端·langchain·agent
回家路上绕了弯6 小时前
当 AI 越来越能干,我们如何理解自己的价值?
后端
陈随易6 小时前
Node.js 2026上半年都有哪些性能提升?
前端·后端·程序员