简体   繁体   中英

Overriding parent class protected member variable annotations in spring

I came across the problem today using SpringBoot where I have a parent abstract class that defines a protected field like this with a spring annotation..

@Length(max=100)
protected String uuid;

In my subclass the max value for the @Length annotation needs to be set to a different value and I'm racking my brain on how to do this. After reading around I suspect there is a way to set annotations on class member variables in class constructors this way I could define the @Length annotation for the member variable uuid and then override the value in the child constructor but have not found any examples or documentation if this is even possible. Any ideas or examples on how to override parent protected variable annotations in a subclass using spring would be greatly appreciated.

This is the full set of Annotations being used...

@ApiModelProperty("Unique ID For My Object")
@Length(max=100)
@Pattern(regexp = "\\S*")
protected String uniqueId

In java there is no such thing as overriding of variables. Only methods can be overriden. This last statement makes come an idea on how to solve the issue. If you don't specify the annotation on the property directly but instead on the getter of the particular field like so for instance:

class Parent{
   private String uniqueId;

   ...

   @ApiModelProperty("Unique ID For My Object")
   @Length(max=100)
   @Pattern(regexp = "\\S*")
   public String getUniqueId(){
      return uniqueId;
   }
}

Then you can override those properties in a child class by overriding the getter:

class Child extends Parent{
   private String uniqueId;

   ...

   @ApiModelProperty("Unique ID For My Object")
   @Length(max=200)
   @Pattern(regexp = "\\S*")
   public String getUniqueId(){
      return uniqueId;
   }
}

I have not checked whether those annotation can be applied on getters also, but I would expect so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM