在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
...
其中的api和implementation是不是很眼熟?這些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"))
}
}
}