Gradle:如何在java中以编程方式声明对项目特定配置的依赖关系
Posted
技术标签:
【中文标题】Gradle:如何在java中以编程方式声明对项目特定配置的依赖关系【英文标题】:Gradle: how to declare a dependency to a specific configuration of a project programatically in java 【发布时间】:2022-01-20 13:46:24 【问题描述】:按照Simple sharing of artifacts between projects 中描述的设置,我们处于一种特殊情况,即我们有一个生成不同类型 jar 的多模块 gradle 构建,我们希望在配置中声明对这些 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.
【问题讨论】:
【参考方案1】: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)
)
)
【讨论】:
以上是关于Gradle:如何在java中以编程方式声明对项目特定配置的依赖关系的主要内容,如果未能解决你的问题,请参考以下文章