Gradle:如何在 java 中以编程方式声明对项目特定配置的依赖

Gradle: how to declare a dependency to a specific configuration of a project programatically in java

按照 Simple sharing of artifacts between projects 中描述的设置,我们处于特殊情况下,我们有一个多模块 gradle 生成生成不同类型的 jar,我们想声明对那些的依赖配置中的 jar。

dependencies {
    instrumentedClasspath(project(path: ":producer", configuration: 'instrumentedJars'))
}

来自文档的效果很好。

在项目dependency-tests中,我有一个重现设置的项目(名称不同,但思路相同)。


但我在 Gradle-插件中这样做,我想在 java.

中有相同的声明
DependencyHandler dependencyHandler = project.getDependencies();

// this adds a dependency to the main jar of the 'producer' project:
dependencyHandler.add("instrumentedClasspath", project.getRootProject().findProject(":producer"));

// this is not working:
dependencyHandler.add("instrumentedClasspath", project.getRootProject().findProject(":producer").getConfigurations().getByName("instrumentedJars"));

失败:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':printConf'.
> Could not resolve all dependencies for configuration ':instrumentedJars'.
   > Cannot convert the provided notation to an object of type Dependency: configuration ':producer:instrumentedJars' artifacts.
     The following types/formats are supported:
       - Instances of Dependency.
       - String or CharSequence values, for example 'org.gradle:gradle-core:1.0'.
       - Maps, for example [group: 'org.gradle', name: 'gradle-core', version: '1.0'].
       - FileCollections, for example files('some.jar', 'someOther.jar').
       - Projects, for example project(':some:project:path').
       - ClassPathNotation, for example gradleApi().
     
     Comprehensive documentation on dependency notations is available in DSL reference for DependencyHandler type.

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

project(...)

dependencies 块内来自 DependencyHandler,并且

path: ":producer", configuration: 'instrumentedJars'

实际上是一个地图{"path"=":producer", "configuration"="instrumentedJars"}。

所以类似的东西应该在 Java:

Map<String, String> map = new HashMap<>();
map.put("path", ":producer"); 
map.put("configuration", "instrumentedJars");
dependencyHandler.add("instrumentedClasspath", dependencyHandler.project(map)); 

注意:使用 Kotlin 构建脚本时,您可以轻松查看函数的类型和声明,并且可能更容易发现 API。所以在 Kotlin 中 project(...)dependencies 块中是一个扩展方法定义为:

fun DependencyHandler.project(
    path: String,
    configuration: String? = null
): ProjectDependency =
    uncheckedCast(
        project(
            if (configuration != null) mapOf("path" to path, "configuration" to configuration)
            else mapOf("path" to path)
        )
    )