[Gradle] 编译任意地方的文件
gradle 对于参与编译的文件的位置没有限制,不必发布到maven repository 或者编译成aar、jar。
SourceSet(添加代码)
在没有特殊处理的场景下,会通过我们添加的插件识别默认的sourceSet。
我们创建一个全新的kotlin 项目,查看他的sourceSet。
//build.gradle.kts
kotlin.sourceSets.forEach {
println(it.name)
}
输出内容
> Configure project :
main
/Users/storytellerF/IdeaProjects/test/src/main/kotlin
/Users/storytellerF/IdeaProjects/test/src/main/java
test
/Users/storytellerF/IdeaProjects/test/src/test/kotlin
/Users/storytellerF/IdeaProjects/test/src/test/java
此方法用于导入annotation processor,kotlin symbols processor 生成的代码。曾经也用来复用gradle plugin 的代码,代码要放到buildSrc 用于调试,但是buildSrc 不能将gradle plugin 发布出去,所以还需要另一个module 用于发布,就将buildSrc 中的代码导入到了module 中,这种方法还导致一个警告⚠️,不过现在有了更好的办法, 后面会讲。
include (添加模块)
一般来说我们添加一个module,会在settings.gradle 中添加这个module
include 'module'
添加的module 默认目录就是当前项目的根目录,不过我们可以覆盖掉指定一个新的路径,这个路径几乎可以是任意位置。
// include two projects, 'foo' and 'foo:bar'
// directories are inferred by replacing ':' with '/'
include 'foo:bar'
// include one project whose project dir does not match the logical project path
include 'baz'
project(':baz').projectDir = file('foo/baz')
// include many projects whose project dirs do not match the logical project paths
file('subprojects').eachDir { dir ->
include dir.name
project(":${dir.name}").projectDir = dir
}
我一般用这个方法导入本地项目或者submodule 的代码。本地项目没有发布,还有很多问题,发布出去在导入调试起来非常不便。或者是submodule,本身就不希望发布成一个库,用这种方式非常适合。并且settings.gradle.kts或者settings.gradle 应该是图灵完备的,支持条件判断,循环,读取外部数据。比如这样:
def baoFolder = ext.baoFolder
def home = System.getProperty("user.home")
def debugBaoFolder
if (baoFolder == "local")
debugBaoFolder = file("$home/AndroidStudioProjects/Bao/")
else
debugBaoFolder = null
if (debugBaoFolder != null && debugBaoFolder.exists()) {
def l = new String[]{
"startup", "bao-library"
}
for (sub in l) {
include("bao:$sub")
project(":bao:$sub").projectDir = file("${debugBaoFolder.absolutePath}/$sub")
}
}
Bao 是一个用于兜底thread exception的。通过上面的代码,就能够通过gradle.properties 决定是导入maven 还是导入本地代码。
includeBuild (添加项目)
构建顺序早已其他模块,本质是另一个项目,可以文件系统中任意的位置。
可以通过设置gradle 的方式引入gradle。
pluginManagement {
includeBuild("../../common-ui-list/version-manager")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
上面的includeBuild
传入的参数是相对路径,同样的路径也被导入到了另一个项目,然后在当前项目(不是上述的version-manager)中当作一个gradle plugin引入。
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("kotlin-parcelize")
id("androidx.navigation.safeargs.kotlin")
id("com.storyteller_f.version_manager")
}
和你猜测的一样,通过includeBuild 引入的项目只能在build.gradle 中使用。如果想要通过implementation 引入,需要知道这个插件的classpath,上面我们指定的com.storyteller_f.version_manager 其实是这个插件的pluginId。我现在还不知道应该如何获取这个classpath。
最后
如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。
如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。
全套视频资料:
一、面试合集
二、源码解析合集
三、开源框架合集
欢迎大家一键三连支持,若需要文中资料,直接扫描文末优快云官方认证微信卡片免费领取↓↓↓
PS:群里还设有ChatGPT机器人,可以解答大家在工作上或者是技术上的问题