Java 如何读取属性文件并使用项目 Gradle 脚本中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37101589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:00:34  来源:igfitidea点击:

How to read a properties files and use the values in project Gradle script?

javagradlegroovy

提问by unknown

I am working on a Gradle script where I need to read the local.propertiesfile and use the values in the properties file in build.gradle. I am doing it in the below manner. I ran the below script and it is now throwing an error, but it is also not doing anything like creating, deleting, and copying the file. I tried to print the value of the variable and it is showing the correct value.

我正在处理一个 Gradle 脚本,我需要在其中读取local.properties文件并使用build.gradle. 我正在按照以下方式进行操作。我运行了下面的脚本,它现在抛出一个错误,但它也没有做任何事情,比如创建、删除和复制文件。我试图打印变量的值,它显示了正确的值。

Can someone let me know if this is correct way to do this? I think the other way is to define everything in the gradle.propertiesand use it in the build.gradle. Can someone let me know how could I access the properties in build.gradlefrom build.properties?

有人可以让我知道这是否是正确的方法吗?我认为,另一种方式是在定义的一切gradle.properties,并在使用它build.gradle。有人可以让我知道如何访问build.gradlefrom 中的属性build.properties吗?

build.gradlefile:

build.gradle文件:

apply plugin: 'java'

//-- set the group for publishing
group = 'com.true.test'

/**
 * Initializing GAVC settings
 */
def buildProperties = new Properties()
file("version.properties").withInputStream {
        stream -> buildProperties.load(stream)
}
//if jenkins build, add the jenkins build version to the version. Else add snapshot version to the version.
def env = System.getenv()
if (env["BUILD_NUMBER"]) buildProperties.test+= ".${env["BUILD_NUMBER"]}"
version = buildProperties.test
println "${version}"

//name is set in the settings.gradle file
group = "com.true.test"
version = buildProperties.test
println "Building ${project.group}:${project.name}:${project.version}"

Properties properties = new Properties()
properties.load(project.file('build.properties').newDataInputStream())
def folderDir = properties.getProperty('build.dir')
def configDir = properties.getProperty('config.dir')
def baseDir  = properties.getProperty('base.dir')
def logDir  = properties.getProperty('log.dir')
def deployDir  = properties.getProperty('deploy.dir')
def testsDir  = properties.getProperty('tests.dir')
def packageDir  = properties.getProperty('package.dir')
def wrapperDir  = properties.getProperty('wrapper.dir')


sourceCompatibility = 1.7
compileJava.options.encoding = 'UTF-8'

repositories {
     maven { url "http://arti.oven.c:9000/release" }
  }

task swipe(type: Delete) {
         println "Delete $projectDir/${folderDir}"
         delete "$projectDir/$folderDir"
         delete "$projectDir/$logDir"
         delete "$projectDir/$deployDir"
         delete "$projectDir/$packageDir"
         delete "$projectDir/$testsDir"
         mkdir("$projectDir/${folderDir}")
         mkdir("projectDir/${logDir}")
         mkdir("projectDir/${deployDir}")
         mkdir("projectDir/${packageDir}")
         mkdir("projectDir/${testsDir}")
}
task prepConfigs(type: Copy, overwrite:true, dependsOn: swipe) {
    println "The name of ${projectDir}/${folderDir} and ${projectDir}/${configDir}"
    from('${projectDir}/${folderDir}')
    into('${projectDir}/$configDir}')
    include('*.xml')
}

build.propertiesfile:

build.properties文件:

# -----------------------------------------------------------------
# General Settings
# -----------------------------------------------------------------
application.name  = Admin
project.name = Hello Cool

# -----------------------------------------------------------------
# ant build directories
# -----------------------------------------------------------------
sandbox.dir = ${projectDir}/../..
reno.root.dir=${sandbox.dir}/Reno
ant.dir = ${projectDir}/ant
build.dir = ${ant.dir}/build
log.dir  = ${ant.dir}/logs
config.dir = ${ant.dir}/configs
deploy.dir  = ${ant.dir}/deploy
static.dir =  ${ant.dir}/static
package.dir = ${ant.dir}/package
tests.dir = ${ant.dir}/tests
tests.logs.dir = ${tests.dir}/logs
external.dir = ${sandbox.dir}/FlexCommon/External
external.lib.dir = ${external.dir}/libs

采纳答案by blacktide

If using the default gradle.propertiesfile, you can access the properties directly from within your build.gradlefile:

如果使用默认gradle.properties文件,您可以直接从build.gradle文件中访问属性:

gradle.properties:

gradle.properties

applicationName=Admin
projectName=Hello Cool

build.gradle:

build.gradle

task printProps {
    doFirst {
        println applicationName
        println projectName
    }
}

If you need to access a custom file, or access properties which include .in them (as it appears you need to do), you can do the following in your build.gradlefile:

如果您需要访问自定义文件,或访问其中包含的属性.(看起来您需要这样做),您可以在您的build.gradle文件中执行以下操作:

def props = new Properties()
file("build.properties").withInputStream { props.load(it) }

task printProps {
    doFirst {
        println props.getProperty("application.name")
        println props.getProperty("project.name")
    }
}

Take a look at this section of the Gradle documentationfor more information.

查看Gradle 文档的这一部分以获取更多信息。

Edit

编辑

If you'd like to dynamically set up some of these properties (as mentioned in a comment below), you can create a properties.gradlefile (the name isn't important) and require it in your build.gradlescript.

如果您想动态设置其中一些属性(如下面的评论中所述),您可以创建一个properties.gradle文件(名称不重要)并在build.gradle脚本中要求它。

properties.gradle:

properties.gradle

ext {
    subPath = "some/sub/directory"
    fullPath = "$projectDir/$subPath"
}

build.gradle

build.gradle

apply from: 'properties.gradle'

// prints the full expanded path
println fullPath

回答by Raman Sahasi

We can use a separate file (config.groovyin my case) to abstract out all the configuration.

我们可以使用一个单独的文件(config.groovy在我的例子中)来抽象出所有的配置。

In this example, we're using three environments viz.,

在这个例子中,我们使用了三个环境,即

  1. dev
  2. test
  3. prod
  1. 开发
  2. 测试
  3. 产品

which has properties serverName, serverPortand resources. Here we're expecting that the third property resourcesmay be same in multiple environmentsand so we've abstracted out that logic and overridden in the specific environment wherever necessary:

它具有属性serverNameserverPortresources在这里,我们期望第三个属性资源在多个环境中可能相同,因此我们抽象出该逻辑并在必要时在特定环境中覆盖:

config.groovy

config.groovy

resources {
    serverName = 'localhost'
    serverPort = '8090'
}

environments {
    dev {
        serverName = 'http://localhost'   
        serverPort = '8080'
    }

    test {
        serverName = 'http://www.testserver.com'
        serverPort = '5211'
        resources {
            serverName = 'resources.testserver.com'
        }
    }

    prod {
        serverName = 'http://www.productionserver.com'
        serverPort = '80'
        resources {
            serverName = 'resources.productionserver.com'
            serverPort = '80'
        }
    }
}

Once the properties file is ready, we can use the following in build.gradleto load these settings:

属性文件准备好后,我们可以使用以下内容build.gradle加载这些设置:

build.gradle

build.gradle

loadProperties()

def loadProperties() {
    def environment = hasProperty('env') ? env : 'dev'
    println "Current Environment: " + environment

    def configFile = file('config.groovy')
    def config = new ConfigSlurper(environment).parse(configFile.toURL())
    project.ext.config = config
}

task printProperties {
    println "serverName:  $config.serverName"
    println "serverPort:  $config.serverPort"
    println "resources.serverName:  $config.resources.serverName"
    println "resources.serverPort:  $config.resources.serverPort"
}


Let's run these with different set of inputs:

让我们用不同的输入集运行这些:

  1. gradle -q printProperties

    Current Environment: dev
    serverName:  http://localhost
    serverPort:  8080
    resources.serverName:  localhost
    resources.serverPort:  8090
    
  2. gradle -q -Penv=dev printProperties

    Current Environment: dev
    serverName:  http://localhost
    serverPort:  8080
    resources.serverName:  localhost
    resources.serverPort:  8090
    
  3. gradle -q -Penv=test printProperties

    Current Environment: test
    serverName:  http://www.testserver.com
    serverPort:  5211
    resources.serverName:  resources.testserver.com
    resources.serverPort:  8090
    
  4. gradle -q -Penv=prod printProperties

    Current Environment: prod
    serverName:  http://www.productionserver.com
    serverPort:  80
    resources.serverName:  resources.productionserver.com
    resources.serverPort:  80
    
  1. gradle -q printProperties

    Current Environment: dev
    serverName:  http://localhost
    serverPort:  8080
    resources.serverName:  localhost
    resources.serverPort:  8090
    
  2. gradle -q -Penv=dev printProperties

    Current Environment: dev
    serverName:  http://localhost
    serverPort:  8080
    resources.serverName:  localhost
    resources.serverPort:  8090
    
  3. gradle -q -Penv=test printProperties

    Current Environment: test
    serverName:  http://www.testserver.com
    serverPort:  5211
    resources.serverName:  resources.testserver.com
    resources.serverPort:  8090
    
  4. gradle -q -Penv=prod printProperties

    Current Environment: prod
    serverName:  http://www.productionserver.com
    serverPort:  80
    resources.serverName:  resources.productionserver.com
    resources.serverPort:  80
    

回答by Lucas Moyano Angelini

Another way... in build.gradle:

另一种方式......在build.gradle中:

Add :

添加 :

classpath 'org.flywaydb:flyway-gradle-plugin:3.1'

And this :

和这个 :

def props = new Properties()
file("src/main/resources/application.properties").withInputStream { props.load(it) }
apply plugin: 'flyway'
flyway {
    url = props.getProperty("spring.datasource.url")
    user = props.getProperty("spring.datasource.username")
    password = props.getProperty("spring.datasource.password")
    schemas = ['db_example']
}