Search code examples
javaspring-bootobjectmicroservicesencapsulation

How to deal with objects of classes that are irrelevant to the microservice?


I am trying to divide a monolithic system into microservices using Spring Boot. The problem I encountered is that while each microservice should normally have classes that implement the service functionality, I need to receive and deal with objects that encapsulate many classes that are related to other microservices. For example, the code below is part of microservice1, which provides student information:

class Microservice1{

int id;
String name;
int grade;
Record record;

}

Notice now that the Record object is of a class that belongs to another microservice, which is microservice2, which provide student record as the following:

class Microservice2{

List<int> marks;
Behaviour behaviour;

}

Now behaviour is also another object whose class belongs to another microservice 3, and so on.

My question is: How do I get rid of the issue of having to include all these classes in microservice 1 because microservice1 needs to deal with them while providing the service? The problem is serious because I have many encapsulated classes inside each other, and I would need to include most of the monolithic system classes in one microservice.


Solution

  • As far as i can see, you are making your microservices way too granular. You'll have a lot of trouble implementing that way.

    IMHO, if a Record is related to a Student AND belongs to the same business context, they belong to the same microservice.

    As David said in the comments, Bounded Contexts concept can (really) help you.

    Anyway, imagine that you want to follow in that line which you're proposing. If a Record belongs to Microservice B and you have to reference it by composition somewhere in Microservice A, the only thing you'll need, is it's primary key. Not the whole object.

    Would be something like this:

    Microservice A:

    Student.java

    public class Student {
    
        private Integer id;
        private String name;
        private Integer grade;
        private Integer recordId;
    
        // getters and setters omitted for brevity
    }
    

    Microservice B:

    Record.java

    public class Record {
    
        private Integer recordId;
        private List<Integer> marks;
        private Integer behaviourId;
    
        // getters and setters omitted for brevity
    }
    

    And so on..

    But as I said, maybe this is not the best approach.

    See here a good article on Bounded Context.