在Gradle的源码注释文档关于依赖项中提到:
* 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.
也就是说一个Project中所有的依赖项都是通过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其实就是对应于你在build.gradle
文件中的
dependencies {
implementation 'group:name:version'
...
}
了解了这些后我们就可以知道怎么在我们自定义的插件中为Project加入依赖项了:
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"))
}
}
}
网友评论