This question already has an answer here:
I am trying to make something like Chain of Resposibility in Spring. My approach assumes that each element of the chain will be called sequentially from one place in code, so I prepared following interface:
public interface RequestValidator {
boolean check(Request request);
}
Now I have a few Components which implements RequestValidator interface. It's time to implement the chain functionality:
@Component
public class ValidationService {
List<RequestValidator> validatorList;
public boolean validateRequest(Request request) {
boolean result = true;
for (RequestValidator validator : validatorList) {
result &= validator.check(request);
}
return result;
}
}
It almost works, the main problem is that I cannot figure out how to create validatorList nicely. The simpliest approach would be to inject necessary validators and create a list of them - but it would make me sick if there were 100 validators in the future.
I know that list of validators can be defined in xml configuration or it can even be constructed in @Configuration class in @Bean method. But.. isn't there any easier way of doing that? Any mechanism of auto-detection of which components implement my interface which would automatically put them in the list?
Aucun commentaire:
Enregistrer un commentaire