我想编写一个小型 SE 应用程序来运行特定于操作系统的命令。这些命令作为“插件”提供给主应用程序,以便能够在运行时添加新的命令实现。这是一个强制性要求:执行新插件不需要重新部署主应用程序。
因此,我开始尝试使用 CDI 进行设置:
// On a common dependency
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Plugin {
String value();
}
public interface Pluggable {
void execute(PluginContext context);
}
插件实现将是这样的(在单独的 jar 中):
@Plugin("greeting")
public class GreetingPlugin implements Pluggable {
public void execute(PluginContext context) {
String greet = context.get("hello.world");
System.out.println(String.format("Hello, %s", greet));
}
}
这很好用,当使用以下注入点加载时,加上一个 select() 调用:
@Inject @Any Instance<Pluggable> plugin;
但是,我想知道添加在运行时添加类的能力的最佳方法是什么,以便将新文件添加到“插件”目录的事件自动将其注册到 ClassLoader和Weld 容器上。
有什么建议么?我还没有考虑过的陷阱?我在 CDI 方面的经验相当有限,也许它甚至可能不是解决这个问题的合适选择。
免责声明由于公司许可政策,OSGI 被排除在外。在这方面无能为力。