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加载进来,在访问新加载进来的接口测试
相关推荐
Flynt4 分钟前
我试了Spring Boot 4的原生镜像,聊聊那些数字和坑
java·spring boot
凤山老林7 分钟前
复杂检索引擎落地:Spring Boot + Elasticsearch 数据同步与高阶查询实战
spring boot·后端·elasticsearch
笃行3508 小时前
SQLServer数据迁移之后,那张报表还能不能秒出
后端
LucianaiB8 小时前
别再被 AI 骗了:我把腾讯云 4 个 Skill 做成了个「AI 打假侦探」,过程的一个小配置坑惨了我
后端
candyTong9 小时前
Claude Code 如何恢复一段会话
后端·架构·ai编程
En^_^Joy10 小时前
Django项目配置全攻略:settings配置文件
后端·python·django
砍材农夫10 小时前
spring-ai|Spring‑AI 2.0.0 新特性 + 入门教程
spring boot·spring·spring cloud
IT_陈寒12 小时前
Python线程池吞了异常还不告诉我,这谁顶得住啊
前端·人工智能·后端
小强库计算机毕业设计13 小时前
SpringBoot+Vue3 学生宿舍管理系统实战
java·spring boot·后端·vue·学生宿舍管理系统
小狼18313 小时前
实践6|SDD 实战:AI 写的规格被推翻了四次
后端·claude