gpt4 book ai didi

java - 如何添加对另一个模块的运行时依赖?

转载 作者:行者123 更新时间:2023-11-30 02:49:27 25 4
gpt4 key购买 nike

我正在为一个由多个 Maven 模块组成的库编写扩展。我需要在一个模块之上添加一些功能,但不想添加不必要的依赖项,以防有人想要在没有我的扩展的情况下使用此模块(典型用例)。

我能想到的一个解决方案是使用我的扩展创建另一个模块,并尝试使用反射从其类中调用方法。会有类似这样的检查:

try {
Class.forName("my.package.Foo", false, getClass().getClassLoader());
// extension will be enabled and some method will be called using reflection
} catch(ClassNotFoundException e) {
// extension will be disabled
}

并且该类上的方法只有在类路径上时才会被调用。如果您在其模块上添加 Maven 依赖项(除了对其扩展的模块的依赖项之外),则可以激活该扩展。

但这听起来并不是最好的方法。有没有更优雅的解决方案来解决这个问题?

最佳答案

一种方法是使用内置 Service provider interface (SPI)

基本思想是让您的可选库提供某些接口(interface)(“服务”)的实现,这些接口(interface)可以很容易地被您的主应用程序找到。看看这个例子

// scan classpath for all registered 
// implementations of Module interface
ServiceLoader<Module> loader = ServiceLoader.load(Module.class);
for (Module module : loader) {
module.doSomething();
}

一旦您的可选依赖项位于类路径中,服务加载器就会找到它。

你可以在 "Creating Extensible Applications" 中找到很多例子Oracle 提供的有关如何制作它的教程。

另一种方法是使用依赖注入(inject)框架,例如 springgoogle guice 。这些框架还提供了用于自动组件发现的类路径扫描机制。该解决方案比 SPI 更灵活,但也更重。

关于java - 如何添加对另一个模块的运行时依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39172232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com