首页 > 解决方案 > 如何使用 Gradle 将配置文件从 jar 中拆分出来

问题描述

我是 Gradle 新手,在新项目中,我尝试使用 Gradle 4 来管理和编译项目。任务 installDist 用于生成分发文件夹。Gradle 将类和所有配置压缩到 jar 文件中,它工作正常,但我想要一个仅在独立文件夹中包含类和配置的 jar。

这是我的源文件夹结构:

src
--main
  --java
  --resources

这是当前的 dist 文件夹结构:

build
--install
  --${project.name}
    --bin
    --lib

但我想要下面的东西:

build
--install
  --${project.name}
    --bin
    --lib
    --resources

而且我想启动脚本也应该修改,现在我编写了一个这样的 CreateStartScripts 任务:

task testServer(type: CreateStartScripts) {
    mainClassName = 'com.xxx.test.Server'
    applicationName = 'test-server'
    outputDir = new File(project.buildDir, 'tmp')
    classpath = jar.outputs.files + project.configurations.runtime
}

有人可以帮我写 Gradle 脚本吗?

标签: javagradle

解决方案


3 build.gradle中的修改:

  1. 禁止将配置文件构建到 jar 中:

    processResources {
        // if you have any other file suffix, append them below
        exclude '*.properties', '*.xml'
    }
    
  2. 将配置文件复制到 dist 文件夹:

    apply plugin: 'distribution'
    
    installDist.doLast {
        copy {
            from 'src/main/resources/'
            // $rootProject.name defined in settings.gradle
            into "$buildDir/install/$rootProject.name/resources"
        }
    }
    
  3. 将资源文件夹添加到类路径:

    task testServer(type: CreateStartScripts) {
        mainClassName = 'com.XXX.XXX.TestServer'
        applicationName = 'test-server'
        outputDir = new File(project.buildDir, 'tmp')
        classpath = jar.outputs.files + project.configurations.runtime
        classpath += files('src/main/resources')
        // gradle find all classpath files under install/${projectname}/lib defaultly
        // replace lib/resources with resources, thank [Fadeev's solution][1]
        doLast {
            def windowsScriptFile = file getWindowsScript()
            def unixScriptFile = file getUnixScript()
            windowsScriptFile.text = windowsScriptFile.text.replace('%APP_HOME%\\lib\\resources', '%APP_HOME%\\resources')
            unixScriptFile.text = unixScriptFile.text.replace('$APP_HOME/lib/resources', '$APP_HOME/resources')
        }
    }
    

推荐阅读