当前位置: 首页 > news >正文

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

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

  1. 创建jar文件动态加载类

@Component
@Slf4j
public class PluginRegistry {@Autowiredprivate GenericApplicationContext applicationContext;@Autowiredprivate RequestMappingHandlerMapping requestMappingHandlerMapping;private final Map<String, URLClassLoader> loaders = new ConcurrentHashMap<>();public void loadPlugin(String jarPath) throws Exception {// 将 JAR 文件转换为 URLFile 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加载进来,在访问新加载进来的接口测试

相关文章:

  • MATLAB 控制系统设计与仿真 - 34
  • 2000-2017年各省国有经济煤气生产和供应业固定资产投资数据
  • 数据结构——反射、枚举以及lambda表达式
  • 深度解析大屏软件及其优势
  • 零基础上手Python数据分析 (16):DataFrame 常用统计分析方法
  • 私人笔记:动手学大模型应用开发llm-universe项目环境创建
  • java 设计模式 策略模式
  • docker的基础知识
  • 微服务4--服务网关
  • 【Qt】常用显示类控件概述(Label、LCD Number、ProgressBar、Calendar Widget)
  • 用手机也能打《无畏契约》?登录ToDesk即可开玩
  • Edge 浏览器推出 Copilot Vision:免费实时解析屏幕内容;Aqua Voice:极速 AI 语音输入工具丨日报
  • Matter如何终结智能家居生态割据,重构你的居住体验?
  • 最快打包WPF 应用程序
  • 教程:批量提取PDF页面指定区域位置的内容,将内容保存到Excel表格,基于WPF的实现过程和方案,可以提取电子发票等类型的PDF文档,将明细保存表格
  • 【Web前端技术】第二节—HTML标签(上)
  • 【Redis】Redis基本命令(1)
  • 【AI】——结合Ollama、Open WebUI和Docker本地部署可视化AI大语言模型
  • LeetCode每日一题4.17
  • 数据江湖:Node.js 与 SQLite3 的轻量之道
  • 网站留言系统编写代码/百度推广客户端下载安装
  • 潍坊做网站维护费用/市场推广渠道有哪些
  • 哪个网站上可以做代打/营销和运营的区别是什么
  • 软件开发专业培训学校/百度seo推广怎么做
  • 网站建设重点/宁波seo公司网站推广
  • 先做网站后付款/北京网站维护公司