何时使用 plugins.withType(somePlugin).whenPluginAdded

When to use plugins.withType(somePlugin).whenPluginAdded

一个gradle 构建有几个子模块。其中有些应用了 java 插件,有些则没有。我试图仅在应用时配置插件。为此,我在顶级 build.gradle 文件中添加了以下内容:

allprojects {
  plugins.withType(JavaPlugin) {
    //some configuration on the JavaPlugin
  }
}

不过,我也注意到了下面的风格:

allprojects {
  plugins.withType(JavaPlugin).whenPluginAdded {
    //some configuration on the JavaPlugin
  }
}

2.什么时候使用withType(){}式配置和什么时候使用withType().whenPluginAdded{}式配置有什么区别?

当您使用 whenPluginAdded() 时,它会在当前集合上调用 whenObjectAdded()。当您调用 withType() 并传递 Closure 时,它会在当前集合上调用 all(),而后者又会在复制的集合上调用 whenObjectAdded()

所以这两种方法都做同样的事情,但前者制作了插件集合的防御性副本。