META-INF / JAR中的服务与Gradle [英] META-INF/services in JAR with Gradle

查看:186
本文介绍了META-INF / JAR中的服务与Gradle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个插件模块,可以使用 的ServiceLoader 。这需要在 META-INF / services 目录中添加一个文件,该文件以服务接口命名,并包含实现它的类的合格路径。然后你可以通过调用 ServiceLoader.load()来加载这些服务。



这里是一个例子:



假设我们想提供一个名为 org.example.plugins.PluginService 的插件接口。然后,我们在类 org.example.plugins.impl.ExamplePlugin 中提供此服务的实现。



如果我们希望有某种插件机制,我们可以创建一个包含实现的JAR文件。这个JAR文件还必须包含文件 META-INF / services / org.example.plugins.PluginService 。这个文件必须包含一行

  org.example.plugins.impl.ExamplePlugin 

启用 ServiceLoader 来查找实现。如果该JAR文件位于构建路径中,则可以通过调用

  Iterator< PluginService>来加载插件。 it = ServiceLoader.load(PluginService.class).iterator(); 

该迭代器可以让您访问所有由 ServiceLoader找到的插件。



由于某些原因,Gradle不会将文件包含到 META-INF 目录默认。有没有办法让生成的JAR包含这样的文件?



我已经找到方法 metaInf 中的/groovydoc/org/gradle/api/tasks/bundling/Jar.html#metaInf%28groovy.lang.Closure%29> C $ C>罐。但我不知道groovy能够自己找到解决方案。 src / main / java 中,但它不是源代码,它是一个资源文件,因此它应该根据Maven目录布局约定放置在资源文件夹中,也就是

  src / main / resources / META- INF / services / org.example.plugins.PluginService 

在这种情况下,所有东西都应该在盒子外面。


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().

Here is an example:

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.

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

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();

That iterator will give you access too all plugins that are found by the ServiceLoader.

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?

I already found the method metaInf in class Jar. But I don't know groovy good enough to find the solution on my own.

解决方案

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.

这篇关于META-INF / JAR中的服务与Gradle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆