META-INF/services in JAR with Gradle

后端 未结 5 1862
予麋鹿
予麋鹿 2020-12-14 07:06

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 t

相关标签:
5条回答
  • 2020-12-14 07:24

    Meanwhile I found a solution to my problem in a (somewhat) similar Question.

    Adding the following to the gradle.build file, resolves my problem

    jar {
      from ('./src/main/java') {
        include 'META-INF/services/org.example.plugins.PluginService'
      }
    }
    

    Now the JAR file looks as expected

    .
    |- org
    |  `- example
    |     `- plugins
    |        `- impl
    |           `- ExamplePlugin.class
    `- META-INF
       |- MANIFEST.MF
       `- services
          `- org.example.plugins.PluginService
    
    0 讨论(0)
  • 2020-12-14 07:26

    Hopefully they will implement this in the jar task just like ant does. Somebody already worked on it: http://fgaliegue.blogspot.fr/2013/06/gradle-serviceloader-support.html

    0 讨论(0)
  • 2020-12-14 07:35

    Hi Can try this: https://plugins.gradle.org/plugin/com.github.harbby.gradle.serviceloader

    Usage

    serviceLoader {
        serviceInterface 'org.example.plugins.PluginService'
        serviceInterface 'org.example.plugins.PluginService2'
    }
    
    0 讨论(0)
  • 2020-12-14 07:48

    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.

    0 讨论(0)
  • 2020-12-14 07:50

    If you happen to inherit some ant based legacy code that does not follow the maven conventions, the following may help.

    Define your source sets to match the legacy structure, and include a line like this:

    include 'META-INF/services/**'

    In your source sets. This pattern is generic and will pick up all your meta inf services.

    Full example below.

    sourceSets {
        main {
            java {
                srcDir 'src'
                exclude '**/Test*.java'
            }
            resources {
                srcDir 'src'
                include '**/*.xml'
                include 'META-INF/services/**'
            }
        }
        test {
            java {
                srcDir 'src'
                include '**/Test*.java'
    
            }
            resources { srcDir 'resources' }
        }
    }
    
    0 讨论(0)
提交回复
热议问题