Montaire
Montaire

Reputation: 1

Gradle inject root project class path to dependencies

I am building a library, which has separate entry points (like server, gui), with different dependencies. Each entry point is in a separate sub project with its own dependencies.

In the root project, where I start the build from, I want to select the entry point, and only build with that dependencies. That is working.

But I want to instantiate a class (eg MainClass) of the root project from the library entry point and I cant add the root projects class path to the dependency. (Diagram)

Root projects build file looks like this now:

dependencies{
    implementation project(':server')
}

Upvotes: 0

Views: 387

Answers (2)

Montaire
Montaire

Reputation: 1

I solved my problem with Composite build. I added includeBuild '../path-to-lib' in the settings.gradle, Than I created a subproject Project to the library with the proper package and class name. On run it throws an error, that the developer should create this class. Its also important to add all the subprojects to the same group:

allprojects{
    group = 'library-group'
}

In the host project, I can depend on the library:

dependencies{
    implementation module('library-group:suproject')
}

Now Gradle automatically overwrites the Classes on the same route as the documentation suggest, and I can finally inject my host project into the lib, and compile it as a whole.

Upvotes: 0

Valts Mazurs
Valts Mazurs

Reputation: 81

It seems to me that it would be easier to understand and clearer if the entry point projects depended on the core API instead of vice versa. You could have project structure like:

settings.gradle
core/
  build.gradle
  src/
server/
  build.gradle
  src/
gui
  build.gradle
  src/

server and gui project build.gradle files should contain:

dependencies {
  implementation project(':core')
}

The project that uses the library could depend on Server and/or GUI projects and instantiate the necessary class (ServerEntry or GuiEntry) directly.

If you want to be able to switch between different entry point implementations without changing the code in the project that uses the entry point instance I'd suggest using a dependency injection framework (Spring, Guice, Dagger). Dependency injection would help to separate configuration (binding interfaces to classes) from the actual application.

Upvotes: 1

Related Questions