Share library between buildsrc and main project


I am wondering if there is any way the following can be done.

I have a project that has a structure that looks like this:

├── build.gradle
├── buildSrc
│   ├── codegen-util
│   │   └── src...
│   └── codegen-tool
│       └── src...
├── web-service1
│   └── src...
├── web-service2
│   └── src...
└── web-service3
    └── src...

Basically codegen-tool is a used by each of the services to generate some code at build time. This all works perfectly. I’ve reached a point where the code that is generated relies on some utilities in the codgen-util library.

Currently as part of the test step of the codegen-tool some dummy code is generated and compiled; then I run some tests against the generated code. This all works perfectly the way I currently have things set up. What I can’t figure out how to do is add the codegen-util library as a dependency in my web-service projects.

Is there a way I can achieve having the codegen-util project as a dependency in both the codegen-tool tests and the web-services?




Had the same issue (sort of) and I fixed it more or less cleanly by overriding the main SourceSet.
Create a new subproject and in the build.gradle of that project:

plugins {
    id 'java'
sourceSets {
    main {
        java {
            srcDirs 'buildSrc/codegen-util/src/main/java', 'src/main/java'
        resources {
            srcDirs 'buildSrc/codegen-util/src/main/resources', 'src/main/resources'

Bind this subproject as a dependency where needed and this should do the trick.
Nevertheless, when it is possible I try to refactor the project and isolate the code in a shared library.

1 Like


This worked pretty nicely, It’s not quite perfect but it’s neat enough. I also moved the dependencies from the real project into a separate gradle file and then used apply from: to import them to each of the projects.

I have to build the project twice whenever I make changes but it’s pretty small. I guess if i really wanted I could remove the tests from the mirror project to speed things up.