If you've got an interface with a generic type parameter, Spring can use that to only autowire implementations that implement a type parameter you specify.
Interface:
public interface GenericValidator<T> {
public T validate(T object);
}
Foo Validator Class:
@Component
public class FooValidator implements GenericValidator<Foo> {
@Override
public Foo validate(Foo foo) {
//Logic here to validate foo objects.
}
}
Bar Validator Class:
@Component
public class BarValidator implements GenericValidator<Bar> {
@Override
public Bar validate(Bar bar) {
//Bar validation logic here
}
}
You can now autowire these validators using type parameters to decide which instance to autowire.
Interface:
public interface FooService {
public void handleFoo(Foo foo);
}
Class:
@Service
public class FooServiceImpl implements FooService {
/** Autowire Foo Validator **/
@Autowired
private GenericValidator<Foo> fooValidator;
@Override
public void handleFoo(Foo foo) {
foo = fooValidator.validate(foo);
}
}