gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:17 25 4
gpt4 key购买 nike

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

当你应该只使用运行时时,什么是实例?当调用 gradle build 时,所有子依赖项都从 compile 中获取并拉入编译。

例如,当我对调用时打印的内容进行比较时

> 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这有助于解释编译运行时之间的区别,但它只表明运行时是您的代码实际执行依赖项的时间。您什么时候会有运行时依赖性,但没有编译时间?

最佳答案

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

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

关于java - 什么时候在 Java/Gradle 中使用运行时而不是编译时依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45740544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com