首先:我对spring-boot和maven真的很陌生。所以我仍然不明白所有东西是如何连接在一起的。
我想要实现的是我的应用程序的某种插件功能。根据我的研究,似乎最好的方法是ServiceLoader
使用SpringFactoriesLoader
.
根据网上的一些说明,我将两个项目放在一起
JamesApplication 提供了一个应该被实现的接口(de.maxrakete.james.device.domain.DeviceInterface
)。
TemperatureSensor 实现了所述类并以多种方式公开它。
对于
ServiceLoader
在META-INF\services\de.maxrakete.james.device.domain.DeviceInterface文件中的这个内容de.maxrakete.james.plugin.TemperatureSensor.TemperatureSensor
对于
SpringFactoriesLoader
文件META-INF\spring.factories中的这个内容de.maxrakete.james.device.domain.DeviceInterface=de.maxrakete.james.plugin.TemperatureSensor.TemperatureSensor
根据这个页面onApplicationEvent
,我在MainApplication中尝试了两种不同的实现(参见-function ) :
@SpringBootApplication
public class JamesApplication implements ApplicationListener<ApplicationReadyEvent> {
public static void main(String[] args) {
SpringApplication.run(JamesApplication.class, args);
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println("Classpath file: " + url.getFile());
}
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
ServiceLoader<DeviceInterface> loader = ServiceLoader.load(DeviceInterface.class);
loader.iterator();
List<DeviceInterface> foos = SpringFactoriesLoader.loadFactories(DeviceInterface.class, null);
}
}
我正在尝试两种方式来加载 jar,但没有发生任何事情(我应该从插件中获取一些日志消息),但这没有发生。
我运行应用程序的方式是这样的:
java -cp "./plugins/TemperatureSensor-0.0.1-SNAPSHOT.jar" -jar james.war
如您所见,我正在尝试将子文件夹中的 jar 添加到类路径中,但是在 -function 的输出中main
(我尝试打印类路径中的所有文件)我只得到Classpath file: /home/max/folder/james.war
结论
因此,存在三个可能的错误源
- 添加类路径文件的 cli 命令错误
- META-INF 文件夹中的接口声明错误
- 加载器的错误实现
- 也许我以错误的方式编译源代码?
- 错误的配置
pom.xml
我真的不知道问题可能是什么。我试图为您提供尽可能多的信息以及我研究的所有步骤。我希望有人能找到一些我可能忽略的有用线索。
谢谢大家!