欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

是否可以在Gradle中声明一个可用于Java的变量?

程序员文章站 2022-05-26 13:58:56
...

本文翻译自:Is it possible to declare a variable in Gradle usable in Java?

Is it possible to declare a variable in Gradle usable in Java ? 是否可以在Gradle中声明一个可用于Java的变量? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time. 基本上我想在build.gradle中声明一些变量,然后在构建时获取它(显然)。 Just like a pre-processor macros in C/C++... 就像C / C ++中的预处理器宏一样......

An example of declaration would be something like that ... : 宣言的一个例子就是那样......:

android {
    debug {
        A_VAR_RETRIEVABLE_IN_JAVA = 42
    }
    release {
        A_VAR_RETRIEVABLE_IN_JAVA = 42+52
    }
}

Is there a way to do something like that ? 有没有办法做那样的事情?


#1楼

参考:https://stackoom.com/question/1A9tE/是否可以在Gradle中声明一个可用于Java的变量


#2楼

Generate Java Constants 生成Java常量

android {
    buildTypes {
        debug {
            buildConfigField "int", "FOO", "42"
            buildConfigField "String", "FOO_STRING", "\"foo\""
            buildConfigField "boolean", "LOG", "true"
        }

        release {
            buildConfigField "int", "FOO", "52"
            buildConfigField "String", "FOO_STRING", "\"bar\""
            buildConfigField "boolean", "LOG", "false"
        }
    }
}

You can access them with BuildConfig.FOO 您可以使用BuildConfig.FOO访问它们

Generate Android resources 生成Android资源

android {
    buildTypes {
        debug{
            resValue "string", "app_name", "My App Name Debug"
        }
        release {
            resValue "string", "app_name", "My App Name"
        }
    }
}

You can access them in the usual way with @string/app_name or R.string.app_name 您可以使用@string/app_nameR.string.app_name以常规方式访问它们


#3楼

Example using system properties, set in build.gradle, read from Java application (following up from question in comments): 使用系统属性的示例,在build.gradle中设置,从Java应用程序中读取(从注释中的问题跟进):

Basically, using the test task in build.gradle , with test task method systemProperty setting a system property that's passed at runtime: 基本上,使用build.gradletest任务,使用测试任务方法systemProperty设置在运行时传递的系统属性:

apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'

repositories {
    mavenCentral()
    // mavenLocal()
    // maven { url 'http://localhost/nexus/content/groups/public'; }
}

dependencies {
    testCompile 'junit:junit:4.8.2'
    compile 'ch.qos.logback:logback-classic:1.1.2'
}

test {
  logger.info '==test=='
  systemProperty 'MY-VAR1', 'VALUE-TEST'
}

And here's the rest of the sample code (which you could probably infer, but is included here anyway): it gets a system property MY-VAR1 , expected at run-time to be set to VALUE-TEST : 以下是示例代码的其余部分(您可以推断,但无论如何都包含在此处):它获得系统属性MY-VAR1 ,在运行时期望设置为VALUE-TEST

package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  static final Logger log=LoggerFactory.getLogger(HelloWorld.class);
  public static void main(String args[]) {
    log.info("entering main...");
    final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
    System.out.println("(main.out) hello, world: " + val);
    log.info("main.log) MY-VAR1=" + val);
  }
}

Testcase: if MY-VAR is unset, the test should fail: 测试用例:如果未设置MY-VAR ,测试应该失败:

package example;
...
public class HelloWorldTest {
    static final Logger log=LoggerFactory.getLogger(HelloWorldTest.class);
    @Test public void testEnv() {
        HelloWorld.main(new String[]{});
        final String val = System.getProperty("MY-VAR1", "UNSET (TEST)");
        System.out.println("(test.out) var1=" + val);
        log.info("(test.log) MY-VAR1=" + val);
        assertEquals("env MY-VAR1 set.", "VALUE-TEST", val);
    }
}

Run (note: test is passing): 运行(注意:测试正在通过):

$ gradle cleanTest test
:cleanTest
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test

BUILD SUCCESSFUL

I've found that the tricky part is actually getting the output from gradle... So, logging is configured here (slf4j+logback), and the log file shows the results (alternatively, run gradle --info cleanTest test ; there are also properties that get stdout to the console, but, you know, why): 我发现棘手的部分实际上是从gradle获取输出...所以,这里配置日志(slf4j + logback),日志文件显示结果(或者,运行gradle --info cleanTest test ;有还有stdout到控制台的属性,但是,你知道,为什么):

$ cat app.log
INFO Test worker example.HelloWorld - entering main...
INFO Test worker example.HelloWorld - main.log) MY-VAR1=VALUE-TEST
INFO Test worker example.HelloWorldTest - (test.log) MY-VAR1=VALUE-TEST

If you comment out " systemProperty... " (which, btw, only works in a test task), then: 如果您注释掉“ systemProperty... ”(其中,顺便说一下,只能在test任务中使用),那么:

example.HelloWorldTest > testEnv FAILED
    org.junit.ComparisonFailure at HelloWorldTest.java:14

For completeness, here is the logback config ( src/test/resources/logback-test.xml ): 为完整起见,这里是logback配置( src/test/resources/logback-test.xml ):

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>app.log</file>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d %p %t %c - %m%n</pattern>
        </layout>
 </appender>
 <root level="info">
     <appender-ref ref="FILE"/>
</root>
</configuration> 

Files: 文件:

  • build.gradle
  • src/main/java/example/HelloWorld.java
  • src/test/java/example/HelloWorldTest.java
  • src/test/resources/logback-test.xml

#4楼

An example of usage an Api App Key in an Android application (Java and XML) 在Android应用程序中使用Api App Key的示例(Java和XML)

gradle.properties gradle.properties

AppKey="XXXX-XXXX"

build.gradle 的build.gradle

buildTypes {
//...
    buildTypes.each {
        it.buildConfigField 'String', 'APP_KEY_1', AppKey
        it.resValue 'string', 'APP_KEY_2', AppKey
    }
}

Usage in java code 在java代码中的用法

Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));

BuildConfig.APP_KEY_1

Usage in xml code 在xml代码中的用法

<data android:scheme="@string/APP_KEY_2" />

#5楼

You can create build config field overridable via system environment variables during build: 您可以在构建期间通过系统环境变量创建可覆盖的构建配置字段:

Fallback is used while developing, but you can override the variable when you run the build on Jenkins or another tool. 在开发时使用Fallback,但是当您在Jenkins或其他工具上运行构建时,可以覆盖变量。

In your app build.gradle : 在您的app build.gradle中

buildTypes {
        def serverUrl =  '\"' + (System.getenv("SERVER_URL")?: "http://default.fallback.url.com")+'\"'
        debug{
            buildConfigField "String", "SERVER_URL", serverUrl
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "SERVER_URL", serverUrl
        }
    } 

The variable will be available as BuildConfig.SERVER_URL . 该变量将作为BuildConfig.SERVER_URL


#6楼

rciovati's answer is entirely correct I just wanted to add one more tidbit that you can also create variables for every build type within the default config portion of your build.gradle. rciovati的答案是完全正确的我只是想再添加一个小工具,你也可以为build.gradle的默认配置部分中的每个构建类型创建变量。 This would look like this: 这看起来像这样:

android {
    defaultConfig {
        buildConfigField "String", "APP_NAME", "\"APP_NAME\""
    }
}

This will allow you to have access to through 这将允许您访问通过

BuildConfig.App_NAME

Just wanted to make a note of this scenario as well if you want a common config. 如果你想要一个通用的配置,也只是想记下这个场景。