问题
I have a gradle project that consist of 3 parts: client, common and service. There are some classes that are used both in client project and service project, therefore I wanted to create a common module and build a jar from it and then import it in other two projects as a library. I put shared classes in common module, I didnt create the main class because I want to project to only provide other classes, so it looks like this:
Then I tried to import it in other project as a library and build them, but when I try to build it with gradle it throws a bunch of errors about the classes from common module:
I couldnt find any tutorials online how to make a common module with gradle. Any help would be appreciated!
回答1:
Assuming all three modules are part of the same multi-module build then in client\build.gradle
and service\build.gradle
you add:
dependencies {
implementation project(':common')
}
The project(:module)
syntax is described in Project dependencies docs.
However if common
, client
and service
are separate projects and don't share the same root build.gradle
you have to publish the common
module into a shared repository and use it like any regular dependency. Easiest to do with Maven Local repository.
回答2:
In Gradle, modules/subprojects must be included to the settings.gradle
file in root project to make it a part of the whole project.
You can add the module to settings.gradle
similarly to:
rootProject.name = 'gradle-root-project'
include('common') //this adds the module
Later, either the root build script or other modules, if they want to use the common
module classes, they need to declare the common
as their dependency:
dependencies {
implementation project(':common')
//...
}
For example, if you will have another module in the project, let's say client
and this module needs to use the code from the common
module, then the client
module must be included in the settings.gradle
file of the root project and added as dependency to the build.gradle
script of the client
module.
If someone reading that would still similar problems when configuring multimodile projects, then it would be good to check this question Why gradle removes dependency when I build a project, it has a bit longer and more detailed explanation of what might be going on underneath Gradle/IDE project configurations.
If you are going to work more with Gradle, you could take a look at this article about overall insight on Gradle.
来源:https://stackoverflow.com/questions/60685569/how-to-create-common-gradle-project-used-by-other-projects