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加载进来,在访问新加载进来的接口测试
相关推荐
雨落倾城夏未凉2 分钟前
5.通过拷贝构造函数复制一个对象,假如对象的成员中有个指针类型的变量,如何避免拷贝出来的副本中的该成员之下行同一块内存(等价于默认拷贝构造函数有没有缺点)
c++·后端
雨落倾城夏未凉4 分钟前
4.深拷贝VS浅拷贝
c++·后端
dl7437 分钟前
一文看懂spring配置原理
后端
ERP老兵_冷溪虎山10 分钟前
IDEA 幽灵触手实锤!Python 文件一开,Anaconda 全局库让 JDK 编译慢 2-4 秒(附截图证据)
后端
阿华的代码王国18 分钟前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互
写bug写bug19 分钟前
分布式锁的使用场景和常见实现(下)
分布式·后端·面试
Postkarte不想说话19 分钟前
Debian13编译安装FreeSWITCH
后端
SimonKing23 分钟前
Mybatis批量插入,形式不同性能也不同
数据库·后端·程序员
MacroZheng27 分钟前
还在用WebSocket实现即时通讯?试试MQTT吧,真香!
java·spring boot·后端
midsummer_woo1 小时前
基于springboot的IT技术交流和分享平台的设计与实现(源码+论文)
java·spring boot·后端