lundi 20 juillet 2020

OOP design : how to inject the right service at runtime?

I have a OOP design problem and want to have an idea what is the best way to solve it:

I have a simple REST API which uses a IValidator interface:

@RestController
public class RESTResource {

@Autowired
private IValidator validator;

...
@PostMapping(...)
public ResponseEntity<SomeDTO> method(@RequestBody someRequest) {
   validator.validate(someRequest)
}

the validator should validate request based on the type (e.g. man or woman) of the request, so I created two different validators ManValidator and WomanValidator which implement IValidator. I annotate these 2 classes using @Service.

The problem is that Spring is telling me it cannot autowire validator, because there are two beans implementing this interface. But how can I inject the right validator on runtime ? I can't decide what to inject before knowing what type is the someRequest.

Aucun commentaire:

Enregistrer un commentaire