带有 Gradle 的 JAR 中的 META-INF/服务 [英] META-INF/services in JAR with Gradle
问题描述
我想构建一个可以使用 ServiceLoader
.这需要向 META-INF/services
目录添加一个文件,该文件以服务接口命名,并包含实现它的类的限定路径.然后你可以通过调用ServiceLoader.load()
来加载这些服务.
I wanted to build a plugin module that can be loaded with a ServiceLoader
. This requires adding a file to the META-INF/services
directory, that is named after the service interface and that contains the qualifying path to the class that implements it. Then you can load these services by calling ServiceLoader.load()
.
这是一个例子:
假设我们想要提供一个名为 org.example.plugins.PluginService
的插件接口.然后我们在 org.example.plugins.impl.ExamplePlugin
类中提供该服务的实现.
Say we want to provide a plugin interface called org.example.plugins.PluginService
. We then provide an implementation of this service in the class org.example.plugins.impl.ExamplePlugin
.
如果我们想要某种插件机制,我们可以创建一个包含实现的 JAR 文件.此 JAR 文件还必须包含文件 META-INF/services/org.example.plugins.PluginService
.此文件必须包含一行
If we want to have some sort of plugin mechanism, we could create a JAR file, that contains the implementation. This JAR file must also contain the file META-INF/services/org.example.plugins.PluginService
. This file must contain one line
org.example.plugins.impl.ExamplePlugin
启用ServiceLoader
以查找实现.如果该 JAR 文件在构建路径中,您可以通过调用
to enable the ServiceLoader
to find the implementation. If that JAR file is in the build path, you can load the plugin by calling
Iterator<PluginService> it = ServiceLoader.load(PluginService.class).iterator();
那个迭代器也会让你访问ServiceLoader
找到的所有插件.
That iterator will give you access too all plugins that are found by the ServiceLoader
.
出于某种原因,Gradle 默认不会将文件包含到 META-INF
目录中.有没有办法让生成的 JAR 包含这样的文件?
For some reason Gradle doesn't include files into the META-INF
directory by default. Is there a way to let the resulting JAR contain such a file?
我已经找到了方法metaInf
在 Jar
类中.但我不知道 groovy 足够好,无法自己找到解决方案.
I already found the method metaInf
in class Jar
. But I don't know groovy good enough to find the solution on my own.
推荐答案
你把 META-INF/services/org.example.plugins.PluginService
放在 src/main/java
code>,但它不是源文件,它是一个资源文件,因此它应该按照Maven目录布局约定放在resources文件夹中,即
You place META-INF/services/org.example.plugins.PluginService
in src/main/java
, but it's not a source, it's a resource file, therefore it should be placed in resources folder according to Maven directory layout convention, that is
src/main/resources/META-INF/services/org.example.plugins.PluginService
在这种情况下,一切都应该是开箱即用的.
In this case everything should work out of the box.
这篇关于带有 Gradle 的 JAR 中的 META-INF/服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!