Home > Back-end >  Java spring - sharing domain models across projects
Java spring - sharing domain models across projects

Time:07-21

Let's say I have a Book class as below in a library (library does not include spring boot). This needs to be shared across multiple services each maintaining their own DB and could add additional fields to the POJO. One of the services uses spring boot. Can I somehow use the Book class in the library as a domain model and have a JpaRepository created with it?

@Data
public class Book {
    private String title;
    private String isbn;
    private double price;
}

Or is there any other suggestion to share the Book class across different services. I am trying to find a solution where I do not have to duplicate this class across all services.

CodePudding user response:

You should not share Book class between different services. Each of those service has a different understanding of what a "Book" is, especially that you mentioned that they will have different set of extra properties.

Create separate domain classes in each service. Some of properties may repeat, that's fine.

Ideally individual services should share as little as possible (of course a schema of some DTO objects used for inter-service communication may be exception).

CodePudding user response:

It's bad practice to share a model with multiple microservices, because it adds a coupling between these microservices. One of the greatest advanteges of microservices is to develop them independently, wich you will lose with coupling.

See these questions and answers for more details about it:

  • Related