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加载进来,在访问新加载进来的接口测试
相关推荐
宠友信息20 分钟前
资源权限与钱包流水在即时通讯源码后端架构中的设计
java·spring boot·redis·websocket·缓存
地铁潜行者37 分钟前
从单体思维到微服务:服务拆分与组件选型实践
java·后端
花生了什么事o38 分钟前
线程池参数调优:corePoolSize 怎么设置
java·后端
想要成为糕糕手38 分钟前
🚀 从零玩转 Agent 开发:原理、架构与框架实战完全指南
后端
卷无止境40 分钟前
pytest 从零到实战:要想代码好,测试少不了
后端·python
K神44 分钟前
Spring gRPC集成Spring Security OAuth2
后端·grpc
Ai拆代码的曹操1 小时前
Dubbo 直连模式翻车现场:2.7.x 调 3.x 的序列化大坑
后端
Chenyiax1 小时前
AC 自动机原理:把一组关键词编译成一次线性扫描
后端
霸道流氓气质1 小时前
Spring Boot 接入阿里云 RocketMQ 完整指南
spring boot·阿里云·java-rocketmq
程序员cxuan1 小时前
读懂 Claude Code 架构分析系列,第二篇:Claude Code 是怎样启动的?
人工智能·后端·程序员