Gradle 更改资源文件在 JAR 中的目标位置

Gio*_*tta 5 java jar classpath gradle

我正在 Gradle-fing 一个具有以下结构的遗留项目:

root
+--- common
|    \--- config
+--- module1
\--- module2
Run Code Online (Sandbox Code Playgroud)

在原始项目中,config它只是一个文件夹,其中包含针对不同环境组织在子文件夹中的配置文件。它包含一个顶级文件夹props和许多子文件夹,如下所示:

config
\--- props
     +--- prod
     +--- dev
     +--- john
     \--- mike
Run Code Online (Sandbox Code Playgroud)

该项目可以配置为使用任何子文件夹。配置通过如下所示的方法加载:

Config.class.getClassLoader().getResourceAsStream("props/" + ENV + "/" + name);
Run Code Online (Sandbox Code Playgroud)

其中ENV定义环境(它是系统属性),即它可以是proddevmike等,并且name只是要加载的文件的名称。

运行测试时,我需要props在类路径中包含该文件夹。在构建生产工件(JAR 和 WAR)时,我不想避免这种情况,并且仅手动复制我需要的文件,以避免可能的冲突或事故。

所以我决定制作config自己的 Gradle 项目,并将其作为 testCompile 依赖项添加到其他需要配置的模块中。但是,如果我将该props文件夹添加为 Gradle 中的资源文件夹,则该config模块的生成 JAR 文件将展平该文件夹的所有子文件夹props(这是预期的行为),因此上面的代码将会失败。

我的问题是:有没有办法告诉 Gradle 将这些文件复制到名为 props 的子文件夹中,而不是复制到 JAR 的根目录中?

我知道重构项目并移动文件夹很容易,但我们正处于从遗留构建和部署工具过渡的阶段,并且希望尽可能保持原始结构,直到我们可以完全切换到 Gradle。这是一个迭代过程,不可能一蹴而就。所以我需要一个临时解决方案。

Gio*_*tta 5

这就是我最终的做法。这是build.gradle该模块的文件config

apply plugin: 'java'

sourceSets {
  main {
    resources {
      srcDir 'props'
    }
  }
}

// this is to force Gradle to create the JAR used at 
// runtime with the correct folder structure
jar.into('props')

idea.module.iml.withXml {
  def node = it.asNode()
  // this is to force IntelliJ to create the folders 
  // used at runtime with the correct folder ('package') structure
  node.component.content.sourceFolder.@packagePrefix="props"
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理就像一个魅力,因为该config模块只包含 props 文件夹中的资源。呼。