如何跨多个Gradle项目共享样板Kotlin配置?
在Gradle项目中, 典型的Kotlin配置是非常模板化的,我正在寻找一种将其抽象为外部构建脚本的方式,以便它可以被重用。
我有一个工作的解决方案(下面),但是这感觉就像是一个黑客,因为kotlin gradle插件不能用这种方式工作。
从外部脚本中应用任何非标准插件是很麻烦的,因为你不能通过id来应用插件
apply plugin: 'kotlin'
将导致Plugin with id 'kotlin' not found.
简单的(通常)解决方法是通过插件的完全限定的类名应用,即
apply plugin: org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper
在这种情况下抛出一个很好的小异常,表明插件可能不是这样调用的:
Failed to determine source cofiguration of kotlin plugin. Can not download core. Please verify that this or any parent project contains 'kotlin-gradle-plugin' in buildscript's classpath configuration.
所以我设法将一个插件(只是真正的插件的修改版本)一起破解,迫使它从当前的buildscript中找到插件。
kotlin.gradle
buildscript { ext.kotlin_version = "1.0.3" repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" } apply plugin: CustomKotlinPlugin import org.jetbrains.kotlin.gradle.plugin.CleanUpBuildListener import org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper import org.jetbrains.kotlin.gradle.plugin.KotlinPlugin import org.jetbrains.kotlin.gradle.tasks.KotlinTasksProvider /** * Wrapper around the Kotlin plugin wrapper (this code is largely a refactoring of KotlinBasePluginWrapper). * This is required because the default behaviour expects the kotlin plugin to be applied from the project, * not from an external buildscript. */ class CustomKotlinPlugin extends KotlinBasePluginWrapper { @Override void apply(Project project) { // use String literal as KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY constant isn't available System.setProperty("kotlin.environment.keepalive", "true") // just use the kotlin version defined in this script project.extensions.extraProperties?.set("kotlin.gradle.plugin.version", project.property('kotlin_version')) // get the plugin using the current buildscript def plugin = getPlugin(this.class.classLoader, project.buildscript) plugin.apply(project) def cleanUpBuildListener = new CleanUpBuildListener(this.class.classLoader, project) cleanUpBuildListener.buildStarted() project.gradle.addBuildListener(cleanUpBuildListener) } @Override Plugin<Project> getPlugin(ClassLoader pluginClassLoader, ScriptHandler scriptHandler){ return new KotlinPlugin(scriptHandler, new KotlinTasksProvider(pluginClassLoader)); } }
这可以在任何项目中apply from: "kotlin.gradle"
),然后开始运行Kotlin开发。
它工作,我还没有任何问题,但我想知道是否有更好的办法? 每次有新版本的Kotlin时,我都不太喜欢对插件进行更改。
看看星云kotlin插件 。 这似乎非常接近你想要达到的目标。
- Android Studio上的Kotlin(非Android)项目的ClassNotFoundException错误
- Android Studio“没有发现测试”
- Kotlin 1.2.10和Java 9对自动模块有相反的规定吗?
- 使用kotlin的自定义风格中的ClassNotFoundException
- Gradle编译在Linux上找不到tornadofx
- Android Studio 3 Canary中未解决的参考
- 由于app:compileDebugKotlin,Jenkins gradle构建失败
- Spring Boot:Boot Run不能添加addResources = true
- Kotlin Dagger2找不到符号ApplicationModule_ProvideApplicationFactory