目的:
动态加载jar包,实现插件的机制。
示例:
package com.alvin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URL;
import java.net.URLClassLoader;
@SpringBootApplication
@RestController
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@GetMapping("/")
public Boolean test(String query) throws Exception {
String jarPath = "D:\\code\\java-plugin\\plugin1\\target\\plugin1-1.0-SNAPSHOT.jar";
String className = "com.alvin.service.impl.Plugin1";
String methodName = "isTrue";
return (Boolean) exec(jarPath, className, methodName, query);
}
public static Object exec(String jarPath, String className, String methodName, String query) throws Exception {
URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("file:" + jarPath)}, Thread.currentThread().getContextClassLoader());
Class demo = classLoader.loadClass(className);
Object object = demo.newInstance();
Object invoke = demo.getMethod(methodName, String.class).invoke(object, new Object[]{query});
return invoke;
}
}