In gradle, what is the purpose of using a buildSrc
file as a top level, as opposed to just a typical java project layout (src/main/java)?
If I have a layout of
src main java
or
buildSrc src main java
What would be the difference (or the reason for doing this)? Is it more useful in multi module projects? Even for a multi module project, couldn't I do something like
proj1 src proj2 src
And then just have a top level build.gradle (at the same level as proj1
and proj2
) that defines common settings across the projects?
buildSrc should be preferred over script plugins as it is easier to maintain, refactor and test the code. buildSrc uses the same source code conventions applicable to Java and Groovy projects. It also provides direct access to the Gradle API. Additional dependencies can be declared in a dedicated build.
gradle file is located inside your project folder under app/build. gradle.
It can do things such as: Extend the Gradle model (e.g. add new DSL elements that can be configured) Configure the project according to conventions (e.g. add new tasks or configure sensible defaults) Apply specific configuration (e.g. add organizational repositories or enforce standards)
buildSrc
is a separate build whose purpose is to build any tasks, plugins, or other classes which are intended to be used in build scripts of the main build, but don't have to be shared across builds.(*) It wouldn't be possible to build such classes as part of the main build, because they have to exist before the main build's build scripts can even be compiled/evaluated, and Gradle compiles/evaluates all build scripts before it does any work (configuration vs. execution phase).
Compared to putting all build code into build scripts, buildSrc
gives you a way to develop build code more like regular code, as classes that you can test, import into your IDE, etc. It is one way to keep build scripts simple and DRY even for more complicated builds.
buildSrc
is more often seen in multi-project builds simply because larger builds are more likely to implement their own custom tasks and plugins.
Over time, buildSrc
will grow into a more general capability of executing multiple dependent builds in a single Gradle invocation.
(*) Sharing classes across builds is possible but more involved. In particular, you'll need to publish the classes to a repository, and consuming builds have to explicitly import them from there, similar to when sharing production libraries between builds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With