vendredi 20 mai 2022

Manipulate annotated property values as the DTO hits the Spring controller?

Can you manipulate properties (e.g. set null ones to Hello world) annotated with a custom annotation as they are handed over to methods in your controller?

For example, let's assume we have a nested DTO:

public class MyDto {
  @MyAnnotation
  private String myProperty;

  private String unannotatedPropety;

  private InnerEntity innerEntity;

  // Getters and setters omitted for brevity
}

public class InnerEntity {
  
  @MyAnnotation
  private String anotherProperty;
  
  // Getters and setters omitted for brevity
}

@RestController(...)
public class MyController {
  
  @PostMapping(...)
  public Mono<ResponseEntity<MyResponse>> myRequestHandler(@RequestBody Mono<MyEntity> json) {
    // ..
  }
}

I initially thought a ConditionalGenericConverter could do the trick (its signature allows for null values to be converted, and it provides TypeDescriptors for its source and target properties, making introspection a breeze), but for controllers, Spring actually uses HttpMessageConverter for payloads (kudos), it seems, and I didn't want to reinvent the entire Jackson deserializer.

On the other hand, Spring + Hibernate Validator manage to introspect payloads and check all properties for specific annotations, so getting to annotated properties should be possible, I hope...

I could probably use AspectJ, but I want this to work in general, and not rely on the payload being of a specific type (like MyDto)... I'm basically hoping there exists a hook I can use, just like the converters API, that does the heavy lifting of reflection for me...

Is there an (easy) approach to do what I want to do?





Aucun commentaire:

Enregistrer un commentaire