dimanche 3 septembre 2023

How to simplify dependency injection of generic interfaces with multiple implementations in a Java application?

I have an interface that looks like this:

public interface InputsValidator<T> {
    List<MessageEnum> validator(T input);
}

I have multiple implementations for example:

@Component
class AddressInputsValidator implements InputsValidator<Address> {

    @Override
    public List<MessageEnum> validator(Address input) {
        List<MessageEnum> messages = new ArrayList<>();
        // Some actions
        return messages;
    }
}

and

@Component
class ContactInputsValidator implements InputsValidator<Contact> {

    @Override
    public List<MessageEnum> validator(Contact input) {
        List<MessageEnum> messages = new ArrayList<>();
        // Some actions
        return messages;
    }
}

Now, in my Spring Boot service, I need to call multiple validators. Today, if I need 10 validators I need to declare all of them:

@Component
@RequiredArgsConstructor
class MyServiceApiImpl extends DelegateHelper implements UserApiDelegate {

    private final InputsValidator<Address> addressInputsValidator;
    private final InputsValidator<Contact> contactInputsValidator;
    ....
}

Is there an elegant way or design pattern to replace all these InputsValidator declarations of each type, with only generic one? For example

@Component
@RequiredArgsConstructor
class MyServiceApiImpl extends DelegateHelper implements UserApiDelegate {

    private final InputsValidator<T> inputsValidator; // Wrong solution
    ....
}

Aucun commentaire:

Enregistrer un commentaire