什么时候在Java / Gradle中使用运行时而不是编译时依赖项?

时间:2017-08-17 16:30:00

标签: java gradle runtime compile-time

根据我的理解,Gradle会将所有compile个依赖项作为runtime依赖项继承。

只应使用runtime时的实例是什么?所有子依赖项都从compile中获取,并在调用gradle build时进入编译。

例如,当我调用

时打印的内容时,我会做差异
> gradle -q dependencies

编译运行时打印的列表完全相同。两个示例输出可能会显示以下内容:

+--- org.springframework.boot:spring-boot-starter-web: -> 1.5.4.RELEASE
|    +--- org.springframework.boot:spring-boot-starter:1.5.4.RELEASE
|    |    +--- org.springframework.boot:spring-boot:1.5.4.RELEASE
|    |    |    +--- org.springframework:spring-core:4.3.9.RELEASE
|    |    |    \--- org.springframework:spring-context:4.3.9.RELEASE
|    |    |         +--- org.springframework:spring-aop:4.3.9.RELEASE
|    |    |         |    +--- org.springframework:spring-beans:4.3.9.RELEASE
|    |    |         |    |    \--- org.springframework:spring-core:4.3.9.RELEASE
|    |    |         |    \--- org.springframework:spring-core:4.3.9.RELEASE
|    |    |         +--- org.springframework:spring-beans:4.3.9.RELEASE (*)
|    |    |         +--- org.springframework:spring-core:4.3.9.RELEASE
|    |    |         \--- org.springframework:spring-expression:4.3.9.RELEASE
|    |    |              \--- org.springframework:spring-core:4.3.9.RELEASE
|    |    +--- org.springframework.boot:spring-boot-autoconfigure:1.5.4.RELEASE
|    |    |    \--- org.springframework.boot:spring-boot:1.5.4.RELEASE (*)
|    |    +--- org.springframework.boot:spring-boot-starter-logging:1.5.4.RELEASE
|    |    |    +--- ch.qos.logback:logback-classic:1.1.11
|    |    |    |    +--- ch.qos.logback:logback-core:1.1.11
|    |    |    |    \--- org.slf4j:slf4j-api:1.7.22 -> 1.7.25
|    |    |    +--- org.slf4j:jcl-over-slf4j:1.7.25
|    |    |    |    \--- org.slf4j:slf4j-api:1.7.25

我看过这个answer,它帮助解释了一下编译运行时之间的区别,但它只表明运行时就是你的代码实际上执行依赖。你什么时候有运行时依赖,但不是编译时间?

1 个答案:

答案 0 :(得分:6)

典型案例涉及通过反射动态创建类。作为一个人为的例子,请考虑这个应用程序:

package net.codetojoy;

public class App {
    public static void main(String[] args) throws Exception {
        Class c = Class.forName("org.apache.commons.lang3.StringUtils");
        Object object = c.getConstructor().newInstance();
        System.out.println("object is : " + object);
    }
}

它将从Apache Commons Lang创建一个StringUtils对象。 (这个例子很愚蠢;考虑libA将为libB中的类有效地执行此操作的情况。

没有编译时依赖性,因此没有理由用jar来加载编译时类路径。但是在运行时,肯定需要jar。 build.gradle文件位于下方。它使用application插件,可以很好地将依赖项捆绑到可运行的可交付项中。

apply plugin: 'java'
apply plugin: 'application'

repositories {
    jcenter()
}

dependencies {
    runtime group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'
}

mainClassName = 'net.codetojoy.App'

示例输出:

$ gradle run -q
object is : org.apache.commons.lang3.StringUtils@4aa298b7