When you have multiple implementations of the same interface, Spring allows you to autowire them all into a collection object. This example uses a Validator pattern.
public class Foo {
private String name;
private String emailAddress;
private String errorMessage;
/** Getters & Setters omitted **/
}
public interface FooValidator {
Foo validate(Foo foo);
}
@Component(value="FooNameValidator")
public class FooNameValidator implements FooValidator {
@Override
public Foo validate(Foo foo) {
// Validation logic goes here.
}
}
@Component(value="FooEmailValidator")
public class FooEmailValidator implements FooValidator {
@Override
public Foo validate(Foo foo) {
// Different validation logic goes here.
}
}
Now, you can autowire these validators individually or together into a class.
public interface FooService {
void handleFoo(Foo foo);
}
@Service
public class FooServiceImpl implements FooService {
/** Autowire all classes implementing FooValidator interface**/
@Autowired
private List<FooValidator> allValidators;
@Override
public void handleFoo(Foo foo) {
/** You can use all instances from the list **/
for(FooValidator validator : allValidators) {
foo = validator.validate(foo);
}
}
}
It's important to note that if you have more than one implementation of an interface in the Spring IoC container and don't specify which one to use with the @Qualifier
annotation, Spring will throw an exception during startup because it won't know which instance to use.
Note: This example demonstrates autowiring multiple beans of the same type. While this example uses a Validator pattern, it's important to note that for simple validations, there are more straightforward methods available, such as Spring's validation with annotations.
In Spring, you can use the @Autowired
annotation for basic annotation-based autowiring. The @Autowired
annotation can be applied in various ways: constructor injection, field injection, or setter injection.