自定義Gradle插件為Project添加依賴

在Gradle的源碼注釋文檔關(guān)于依賴項(xiàng)中提到:

 * Dependencies
 *
 * A project generally has a number of dependencies it needs in order to do its work.  Also, a project generally
 * produces a number of artifacts, which other projects can use. Those dependencies are grouped in configurations, and
 * can be retrieved and uploaded from repositories. You use the {@link org.gradle.api.artifacts.ConfigurationContainer}
 * returned by {@link #getConfigurations()} method to manage the configurations. The {@link
 * org.gradle.api.artifacts.dsl.DependencyHandler} returned by {@link #getDependencies()} method to manage the
 * dependencies. The {@link org.gradle.api.artifacts.dsl.ArtifactHandler} returned by {@link #getArtifacts()} method to
 * manage the artifacts. The {@link org.gradle.api.artifacts.dsl.RepositoryHandler} returned by {@link
 * #getRepositories()} method to manage the repositories.

也就是說一個(gè)Project中所有的依賴項(xiàng)都是通過Configuration分組最終保存在Configuration的dependencies里面,如果你想知道都有哪些Configuration可以在build.gradle文件中加入

project.configurations.all { configuration ->
                System.out.println("this configuration is ${configuration.name}")
            }

然后在Gradle Console中可以看到所有的Configuration

this configuration is androidJacocoAgent
this configuration is androidJacocoAnt
this configuration is androidTestAnnotationProcessor
this configuration is androidTestApi
this configuration is androidTestApk
this configuration is androidTestCompile
this configuration is androidTestCompileOnly
...
this configuration is api
...
this configuration is implementation
...

其中的apiimplementation是不是很眼熟?這些Configuration其實(shí)就是對應(yīng)于你在build.gradle文件中的

dependencies {
    implementation 'group:name:version'
    ...
}

了解了這些后我們就可以知道怎么在我們自定義的插件中為Project加入依賴項(xiàng)了:

class TestPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {

        project.configurations.all { configuration ->
            def name = configuration.name
            System.out.println("this configuration is ${name}")
            if (name != "implementation" && name != "compile") {
                return
            }
            //為Project加入Gson依賴
            configuration.dependencies.add(project.dependencies.create("com.google.code.gson:gson:2.8.2"))
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容