将Gradle自定义配置任务转为Kotlin DSL时依赖无法解析
解决Gradle Kotlin DSL自定义SourceSet依赖解析问题
原Groovy代码逻辑回顾
你原来的Groovy代码中,自定义dashboard SourceSet后,Gradle会自动生成对应的dashboardImplementation、dashboardRuntimeOnly等配置,这些配置会自动关联到SourceSet的compileClasspath和runtimeClasspath中。dashboardImplementation的依赖会被包含到sourceSets.dashboard.runtimeClasspath,所以generateDashboard任务能正常找到依赖。
你的Kotlin DSL错误点
- 手动创建了独立的
dashboard配置,但这个配置没有关联到SourceSet的类路径中,导致你用dashboard()声明的依赖不会被加入runtimeClasspath。 - 错误使用
dashboard()声明依赖,而不是SourceSet自动生成的dashboardImplementation配置。
正确的Kotlin DSL实现
// 1. 定义自定义SourceSet,Gradle会自动生成对应的配置(dashboardImplementation等) sourceSets.create("dashboard") { java.srcDir("src/dashboard/java") resources.srcDir("src/dashboard/resources") } // 2. 用自动生成的dashboardImplementation声明依赖,该依赖会自动加入到dashboard的runtimeClasspath dependencies { "dashboardImplementation"("some:dep:1.0") // 如果需要runtime依赖,用dashboardRuntimeOnly // "dashboardRuntimeOnly"("another:dep:2.0") } // 3. 注册generateDashboard任务,关联正确的类路径和依赖任务 tasks.register<JavaExec>("generateDashboard") { dependsOn(tasks.named("dashboardClasses")) classpath = sourceSets.getByName("dashboard").runtimeClasspath mainClass.set("com.example.DashboardGenerator") // Kotlin DSL标准setter写法 }
关键说明
- 不需要手动创建
configurations.dashboard,SourceSet创建时Gradle会自动生成一组配套配置,命名规则是[sourceSetName]Implementation、[sourceSetName]RuntimeOnly等,这些配置会自动绑定到SourceSet的类路径中。 - 用字符串形式的依赖配置名称(
"dashboardImplementation")是因为Kotlin DSL默认不会自动生成自定义SourceSet的配置访问器,如果你想使用类型安全的访问器,可以在build.gradle.kts顶部添加plugins { id("java") }后,运行./gradlew kotlinDslAccessorsSnapshot生成访问器,之后就能直接用dashboardImplementation("some:dep:1.0")。 tasks.named("dashboardClasses")是Kotlin DSL中引用任务的正确方式,替代Groovy里直接用dashboardClasses的写法。
内容的提问来源于stack exchange,提问作者codeYogico
相关产品推荐
相关产品推荐

