Spring@AutowiredforListTypes
Let’s see an example - we have three pets that we’d like to register them on the public animal registry.
publicabstractclassAnimal{ ... }
@ComponentpublicclassMyDogextendsAnimal{ ... }
@ComponentpublicclassMyCatextendsAnimal{ ... }
@ComponentpublicclassMyBirdextendsAnimal{ ... }
The question is - how to register all my animals?
@ComponentpublicclassAnimalRegistry{
private Map<String, Animal> registry;
// How to register all my animals to the registry?
}
Naive Approach
@ComponentpublicclassAnimalRegistry{
private Registry<Animal> registry;
/**
* This is naive because if you have more animals,
* you have to specify them explicitly here
*/
@Autowired
publicAnimalRegistry(MyDog dog, MyCat cat, MyBird bird){
registry.register(dog);
registry.register(cat);
registry.register(bird);
}
}
Have Spring Autowire All Subclass
@ComponentpublicclassAnimalRegistry{
private Registry<Animal> registry;
/**
* The problem with this approach is that
* if you don"t have any animals, there"s no bean to be autowired here,
* and Spring will report bean initialization error
*/
@Autowired
publicAnimalRegistry(List<Animal> myAnimals){
if(myAnimals != null && !myAnimals.isEmpty()) {
myAnimals.forEach(a -> registry.register(a));
}
}
}
Better Usage of @Autowired
@ComponentpublicclassAnimalRegistry{
private Registry<Animal> registry;
@Autowired(required = false)
List<Animal> myAnimals;
/**
* This ensures that Spring can still successfully run
* even when there"s no bean to be autowired to "myAnimals"
*/
@PostConstruct
publicvoidinit(){
if(myAnimals != null && !myAnimals.isEmpty()) {
myAnimals.forEach(a -> registry.register(a));
}
}
}
This tip should work well w.r.t interfaces
public inteface Provider { ... }
@ComponentpublicclassDogProviderimplementsProvider{ ... }
@ComponentpublicclassCatProviderimplementsProvider{ ... }
@ComponentpublicclassBirdProviderimplementsProvider{ ... }
@ComponentpublicclassProviderRegistry{
private Registry<Provider> registry;
@Autowired(required = false)
List<Provider> providers;
@PostConstruct
publicvoidinit(){
if(providers != null && !providers.isEmpty()) {
providers.forEach(a -> registry.register(a));
}
}
}
以上是 Spring@AutowiredforListTypes 的全部内容, 来源链接: utcz.com/z/513100.html