How can I apply SpotBugs using a script plugin?

I had something like this in a file ‘myplugin.gradle’ that I would apply to other projects:

apply plugin: MyPlugin

class MyPlugin implements Plugin<Project> {
   void apply(Project project) {
      project.configure(project) {
            apply plugin: 'java'
            apply plugin: 'findbugs'
      }
   }
  // more to it here...
}

Now I need to run with newer Java that FindBugs does not support, so I want to use SpotBugs.

buildscript {
  repositories {
    maven { url "https://plugins.gradle.org/m2/" }
  }
  dependencies {
    classpath "gradle.plugin.com.github.spotbugs:spotbugs-gradle-plugin:1.6.9"
  }
}

apply plugin: MyPlugin

class MyPlugin implements Plugin<Project> {
   void apply(Project project) {
      project.configure(project) {
            apply plugin: 'java'
            apply plugin: 'com.github.spotbugs'
      }
   }
  // more to it here...
}

However it says that “Plugin with id ‘com.github.spotbugs’ not found.” Apparently the class path in the build script block isn’t in effect for a script plugin that is applied to another project with ‘apply from:’ ??

How do I make this work?

I ran into a similar issue to this, and found that declaring the spotbugs dependency at the top level of the plugin’s build.gradle fixed my issue:

dependencies {
    compile "com.github.spotbugs:spotbugs-gradle-plugin:2.0.1"
}

I’m not sure exactly what the difference is yet, but declaring the spotbugs dependency here allows for it to be transitively resolved by the gradle project consuming the plugin.

I will try that, though it should probably be compileOnly configuration, so spotbugs doesn’t become a requirement of the build artifact.