关于应用程序的“可插拔”部分和在文件夹中加载JAR,而不是重新发明轮子,也许你可以看看OSGI。通过使用OSGI实现(
Apache Felix
如果你想要一个可插拔的插件系统,OSGI将处理很多问题。
例如,我是这样做的:
public ChannelListener init() {
private ChannelListener listener = new ChannelListener();
logger.info("Initializing Felix...");
felix = new Felix(getConfig());
try {
felix.start();
} catch (BundleException e) {
logger.error("Error while initializing Felix", e);
throw new RuntimeException(e);
}
try {
// On the next line, you are registering a listener that will listen for all
//Log implementations service registration.
felix.getBundleContext().addServiceListener(listener, "(objectClass=com.company.automation.service.Log)");
} catch (InvalidSyntaxException e) {
logger.error("Error while registering service listener", e);
}
listener.start(felix.getBundleContext());
startAllBundlesInDirectory(BUNDLE_DIRECTORY, felix.getBundleContext());
return listener;
}
private void startAllBundlesInDirectory(String directory, BundleContext context) {
File bundleFolder = new File(directory);
File[] bundleFilesList = bundleFolder.listFiles((dir, name) -> name.endsWith(".jar"));
List<Bundle> installedBundles = new ArrayList<>();
logger.info("Installing {} bundles in {}.", bundleFilesList.length, directory);
for(File bundleFile : bundleFilesList) {
logger.info("Installing {}", bundleFile.getName());
try {
installedBundles.add(context.installBundle("file:" + directory + bundleFile.getName()));
} catch (BundleException e) {
logger.error("Error while installing bundle {}{}", directory, bundleFile.getName(), e);
}
}
for(Bundle bundle : installedBundles) {
try {
bundle.start();
} catch (BundleException e) {
logger.error("Error while starting bundle {}{}", directory, bundle.getSymbolicName(), e);
}
}
}