Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing common code between multiple spring boot APIs

I have two spring boot REST APIs, both of them has exactly same /health endpoint, I want to extract out this endpoint into some other Java project.

I want following things:

  1. When I compile any of the APIs the common module should be compiled

  2. I am using docker containers to run these APIs in separate dockers. How to copy the jar file for the common code into the Dockers.

Please ignore if the question seems silly, I am not sure whether to make the common project as a module or inject that as a dependency in these two project's pom file.

like image 409
Mr_Hmp Avatar asked Oct 21 '25 03:10

Mr_Hmp


1 Answers

Maven can accomplish this task.

I want following things:

When I compile any of the APIs the common module should be compiled

The Maven multi module pom (called also the aggregator pom) achieves that.

1) Couple the three components in terms of build


- api-parent (multimodule pom and parent pom also if needed)
   |
   |____ common-lib (jar)
   |____ api-foo (spring boot fat jar)
   |____ api-bar (spring boot fat jar)

The drawback of this approach is that the version of common-lib is necessarily the same for the two apis modules that use it. But since you want to compile the common-lib at each build of any api, finally that makes sense.

You can use such an approach while you want/need that the version of common-lib be the same between your apis. If later it turns out that the version of common-lib used by your apis should differ because these don't have the same lifecycle, you can decouple them that as the following.

2) Decouple the three components in terms of build

At the same level, defines the common-lib project, and two apis projects and defines in each api project a dependency to common-lib.


- common-lib (jar)

- api-foo (spring boot fat jar)
   |
   |____uses___ common-lib v1 (jar)


- api-bar (spring boot fat jar)
   |
   |____uses___ common-lib v2 (jar)

I am using docker containers to run these APIs in separate dockers. How to copy the jar file for the common code into the Dockers.

You don't copy this library yourself. The spring boot maven plugin creates the fat jar for you that has contains all dependencies that you declared and that are needed for your micro services. So just deploy the jars created by Spring Boot on your docker containers.

Side note :

In both approaches, I think that you should define these three projects in a same SCM repository (the mono repository approach rather than the multi repository approach) because these three components are functionally coupled. You may want to work on all of these at the same time.

like image 126
davidxxx Avatar answered Oct 23 '25 16:10

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!