|
| 1 | +package com.codingapi.springboot.framework.boot; |
| 2 | + |
| 3 | +import lombok.Setter; |
| 4 | +import org.springframework.boot.SpringApplication; |
| 5 | +import org.springframework.context.ConfigurableApplicationContext; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.net.URL; |
| 9 | +import java.net.URLClassLoader; |
| 10 | +import java.nio.file.Files; |
| 11 | +import java.nio.file.Path; |
| 12 | +import java.nio.file.Paths; |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +public class DynamicApplication { |
| 17 | + |
| 18 | + private final static DynamicApplication instance = new DynamicApplication(); |
| 19 | + |
| 20 | + public static DynamicApplication getInstance() { |
| 21 | + return instance; |
| 22 | + } |
| 23 | + |
| 24 | + private DynamicApplication() { |
| 25 | + } |
| 26 | + |
| 27 | + private ConfigurableApplicationContext context; |
| 28 | + private String[] runArgs; |
| 29 | + private Class<?> applicationClass; |
| 30 | + |
| 31 | + @Setter |
| 32 | + private String jarsFolder = "./jars"; |
| 33 | + |
| 34 | + |
| 35 | + public void run0(Class<?> applicationClass, String[] args) { |
| 36 | + this.runArgs = args; |
| 37 | + this.applicationClass = applicationClass; |
| 38 | + context = SpringApplication.run(applicationClass, args); |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + public static void run(Class<?> applicationClass, String[] args) { |
| 43 | + DynamicApplication.getInstance().run0(applicationClass, args); |
| 44 | + } |
| 45 | + |
| 46 | + public static void restart() { |
| 47 | + DynamicApplication.getInstance().restart0(); |
| 48 | + } |
| 49 | + |
| 50 | + public void restart0() { |
| 51 | + Thread thread = new Thread(() -> { |
| 52 | + context.close(); |
| 53 | + try { |
| 54 | + this.addDynamicJars(); |
| 55 | + } catch (IOException e) { |
| 56 | + throw new RuntimeException(e); |
| 57 | + } |
| 58 | + this.run0(applicationClass, runArgs); |
| 59 | + }); |
| 60 | + thread.setDaemon(false); |
| 61 | + thread.start(); |
| 62 | + } |
| 63 | + |
| 64 | + private void addDynamicJars() throws IOException { |
| 65 | + Path libsPath = Paths.get(jarsFolder); |
| 66 | + if (Files.exists(libsPath) && Files.isDirectory(libsPath)) { |
| 67 | + System.out.println("Start Load Dynamic Jars:"); |
| 68 | + List<URL> jarUrls = new ArrayList<>(); |
| 69 | + Files.list(libsPath) |
| 70 | + .filter(file -> file.toString().endsWith(".jar")) |
| 71 | + .forEach(file -> { |
| 72 | + try { |
| 73 | + URL url = file.toUri().toURL(); |
| 74 | + jarUrls.add(url); |
| 75 | + System.out.println(url); |
| 76 | + } catch (Exception ignored) {} |
| 77 | + }); |
| 78 | + URL[] urls = jarUrls.toArray(new URL[0]); |
| 79 | + URLClassLoader urlClassLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); |
| 80 | + Thread.currentThread().setContextClassLoader(urlClassLoader); |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments