Home > Software engineering >  Can Spring Boot annotations in POJOS be configured based on APIs/requests?
Can Spring Boot annotations in POJOS be configured based on APIs/requests?

Time:11-16

I have two APIs referencing the POJO class below.

class Data{
 private String name;  
 private String age;          
 private String address;       
 private String phone_number;
}

I need to annotate the fields in this POJO as below.

class Data
{
 @JsonProperty(required = true) 
 private String name;          // required field
 @JsonProperty(required = true)
 private String age;           // required field
 @JsonInclude( Include.Non_Null)
 private String address;       // optional field
 @JsonIgnore
 private String phone_number;  // ignore field
}

The annotations need to be applied to only one of API.The other API should not be impacted by this change.

One way of achieving this is to create two separate POJOs, one for each API. But is it possible to achieve the results using the same POJO classes? Is there a way to configure the annotations based on which API is being invoked?

CodePudding user response:

Some repetition is not bad especially if they're used for two different purposes.

Ideally these would be in two different packages as well. That way, you don't have a name clash.

If you want to avoid but I do not recommend it is have

class RequiredData extends Data {
   @JsonProperty(required = true)
   void setName(String name) {
     super.setName(name);
   }
}

CodePudding user response:

The annotations need to be applied to only one of API.The other API should not be impacted by this change.

One way of achieving this is to create two separate POJOs, one for each API. But is it possible to achieve the results using the same POJO classes? Is there a way to configure the annotations based on which API is being invoked?

You can create a library containing the classes that two APIs to have to share and introduce it in both APIs as a dependency.

That would allow to ensure both parts of your System will have the same definition of these domain classes.

Note: you need to have a strong reason for doing so. Because there was a reason to implement them as independent APIs and introducing this dependency creates a coupling between them. If there would be a considerable amount of such classes, then as a consequence APIs would not be able to evolve independently.

  • Related