如何使用Gradle将配置文件从jar中分离出来

时间:2018-08-17 09:42:25

标签: java gradle

我是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脚本吗?

1 个答案:

答案 0 :(得分:0)

build.gradle中的3个修改:

  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')
        }
    }