根据我的理解,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,它帮助解释了一下编译和运行时之间的区别,但它只表明运行时就是你的代码实际上执行依赖。你什么时候有运行时依赖,但不是编译时间?
答案 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