Packaging spring sub-projects into one jar

2019-08-18 00:19发布

问题:

I'm having Spring based web-app that I'm trying to bundle into a single jar.

My thoughts on laying out the project was to have a root project that contains multiple sub-projects, where there would be one sub-project that is a spring-boot application, and others sub-projects maybe my own-written code handle certain business logic let's say.

So the structure may look something like:

/root
 build.gradle <- the problem is here, how I should write root project build script
 /spring-backend-subproject
 /other-business-subproject

Having all these sub-projects, I want to package them all into one single JAR, so that I can just do

java -jar build/libs/RootJar.jar

otherwise I need to run:

./gradlew bootRun

which will run the particular main class in the "spring-boot" sub-project

I've been searching online for how to bundle all subproject jars into one jar, such as this one: Can Gradle jar multiple projects into one jar? but I often just end up having errors such as main-class not found(which does not happen if I run the jar specifically in the "spring sub-project" folder) or SpringApplication class not found (again does not happen if run jar in the sub-project folder)

How may I solve this problem?

Thanks!

回答1:

I use this pattern extensively. Instead of trying to put the deployment classes into the root, add a module (I usually call it -launcher) that lists the other modules as dependencies and contains your main class and related application code, such as any application.properties you may have.

This module will produce an artifact my-project-launcher.jar, and you deploy this to whatever platform you're using.