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加载进来,在访问新加载进来的接口测试
相关推荐
canonical_entropy11 分钟前
XDef:一种面向演化的元模型及其构造哲学
后端
小林coding25 分钟前
再也不怕面试了!程序员 AI 面试练习神器终于上线了
前端·后端·面试
lypzcgf29 分钟前
Coze源码分析-资源库-删除插件-后端源码-错误处理与总结
人工智能·后端·go·coze·coze源码分析·ai应用平台·agent平台
文心快码BaiduComate37 分钟前
WAVE SUMMIT深度学习开发者大会2025举行 文心大模型X1.1发布
前端·后端·程序员
SamDeepThinking1 小时前
在Windows 11上配置Cursor IDE进行Java开发
后端·ai编程·cursor
知其然亦知其所以然1 小时前
面试官微笑发问:第100万页怎么查?我差点当场沉默…
后端·mysql·面试
文心快码BaiduComate1 小时前
文心快码升级至3.5S版本,强化多智能体自协同能力
前端·后端·程序员
蒋星熠2 小时前
深入 Kubernetes:从零到生产的工程实践与原理洞察
人工智能·spring boot·微服务·云原生·容器·架构·kubernetes
ponnylv2 小时前
深入剖析Spring Boot自动配置原理
spring boot·spring
即兴小索奇2 小时前
Google AI Mode 颠覆传统搜索方式,它是有很大可能的
前端·后端·架构