Search code examples
javaspring-bootspring-data-jpamicroservices

How to make Super/Base/Parent class in microservices in spring-boot - to extend that class in child class


1) I have 3 microservices project (Country-micro, State-micro and City-micro) with 3 entities Country, State and City in each microservices define respectively. Please note that all 3 microservices has same group id in pom.xml

All the entity has common 4 fields

  1. id
  2. created_date
  3. modified_date
  4. is_active

How can I make base entity class for above fields and use it in different microservices. Like, in monolithic architecture we can use easily by extending class as define here :

My base Class

@MappedSuperclass
@Data
public class BaseEntity {
    private Long id;
    private Date created_date;
    private Date modified_date;
    private Boolean is_active;

}

My child class

@Entity
@Data
@EqualsAndHashCode(callSuper=false)
@Table(name="tbl_country")
public class Country extends BaseEntity {
    private String countryName;
    private String countryCode;
}

But, in microservices architecture, all entities are separated. Then, how can I define service to make as Super class.

2) With the same question above, I also want to use my constant class in each microservices. Like, in monolithic structure, we can :

public interface Constants {
    static String HTTP = "http";
    static String COMMA_AND_SPACE = ", ";
}

And can use this constants in any class like:

public String myMethod(MyDto myDto) {
    StringBuilder sb = new StringBuilder();

    sb.append("My First String").append(Constants.COMMA_AND_SPACE);
    sb.append("My Second String").append(Constants.COMMA_AND_SPACE);
}

In which service I can define constants, Should I create separate service? or I have to define same constants in every microservice (like code redundant). I am also using Utility class in monolithic structure same way.

Please explain structure or guide me to define base classes or Utils.

Thank you in advance.


Solution

  • You can create one new module as Common and put all your common code in it.

    Just add it's dependency in whichever project needed in pom.xml.

    So even if you run Microservice1 separately you will have to bind Common module as well in it.

    eg in Microservice1 pom.xml add common dependency

    <dependency>
        <groupId>com.sample.common</groupId>
        <artifactId>Common</artifactId>
        <version>${project.version}</version>
    </dependency>
    

    Can read this as well