使用 gradle 将依赖信息嵌入到清单中

use gradle to embed dependency information into manifest

我想将依赖信息嵌入到我的清单文件中,以便我可以在运行时公开此信息。即我可以看到我的服务的特定 运行 实例使用了哪个版本的库。

我正在使用 gradle 构建我的 'fatjar':

shadowJar {
  mergeServiceFiles()
  archiveName "service.jar"
  exclude "META-INF/*.SF"
  exclude "META-INF/*.DSA"
  exclude "META-INF/*.RSA"
  manifest {
    attributes('Main-Class': "service.Service",
               'Built-By': System.getProperty('user.name'),
               'Built-Date': new Date(),
               'Built-JDK': System.getProperty('java.version'),
               'Implementation-Version': version,
               'Implementation-Title': project.name)
  }
}

而且我对其他各种库有依赖性:

dependencies {
  compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.39'
  ...
}

如何将依赖信息添加到我的清单文件中?例如:

Manifest-Version: 1.0
Implementation-Title: service
Implementation-Version: Local Build
Built-By: me
Built-Date: Wed Jun 22 14:13:53 BST 2016
Built-JDK: 1.8.0_91
Main-Class: service.Service
Dependency-mysql-connector-java: mysql:mysql-connector-java:5.1.39

可以通过以下方式完成:

buildscript {
  repositories {
    maven {
      url 'https://plugins.gradle.org/m2/'
    }
  }

  dependencies {
    classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3'
  }
}

apply plugin: 'java'
apply plugin: 'com.github.johnrengelman.shadow'

repositories {
  mavenCentral()
}

dependencies {
  compile 'com.google.guava:guava:19.0'
  compile 'com.google.inject:guice:4.1.0'
}

shadowJar {
  mergeServiceFiles()
  archiveName "service.jar"
  exclude "META-INF/*.SF"
  exclude "META-INF/*.DSA"
  exclude "META-INF/*.RSA"
  manifest {
    attributes(
               [
               'Main-Class': "service.Service",
               'Built-By': System.getProperty('user.name'),
               'Built-Date': new Date(),
               'Built-JDK': System.getProperty('java.version'),
               'Implementation-Version': 'version',
               'Implementation-Title': project.name,
               ] +
               project.configurations.compile.allDependencies.collect { d ->
                 [
                  ("dependency-${d.group.replaceAll('\.','-')}".toString()):"$d.group:$d.name:$d.version"
                 ]
               }.sum()
    )
  }
}

上面的脚本生成以下内容MANIFEST.MF

Manifest-Version: 1.0
Main-Class: service.Service
Built-By: opal
Built-Date: Mon Jul 04 17:27:05 CEST 2016
Built-JDK: 1.8.0_91
Implementation-Version: version
Implementation-Title: 37969253
dependency-com-google-guava: com.google.guava:guava:19.0
dependency-com-google-inject: com.google.inject:guice:4.1.0

由于 attributesMap 作为参数,您需要收集它们的依赖关系,将它们转换为 Map 并对映射求和。