Gradle custom plugin : add dependency from extension object

前端 未结 4 641
走了就别回头了
走了就别回头了 2021-02-05 05:07

I\'m trying to write a plugin which adds dependencies to project.dependencies according to informations gathered in the plugin extension object. But it seems to be

4条回答
  •  自闭症患者
    2021-02-05 05:57

    I originally implemented this solution using the DependencyResolutionListener approach by Saad. However, the listener itself is called only when something iterates over the configuration associated with the dependency. For example, if you want to dynamically add a dependency to compile, you have to make sure that something later on does something like:

    project.configurations.compile.each {
       ...
    }
    

    But this is something that happens as a matter of course, since compile is a known configuration for any project that uses the java plugin. However, if you are using a custom configuration (as I was), then the listener approach won't work unless you explicitly iterate over your custom configuration.

    I was able to find a better way to do this, and within afterEvaluate as the OP originally wanted. I'm using a custom configuration here, but I don't see a reason why it wouldn't work for compile either:

    project.afterEvaluate {
        def version = project.myPlugin.version
        project.configurations.myConfig.dependencies.add(
            project.dependencies.add("myConfig", "org.foo:bar:$version")
        )
    }
    

    Of course, at some point something still has to iterate over the dependencies for them to actually get resolved.

提交回复
热议问题