I have some Spring Beans of a specific type but with different names:
@Bean public Car audi() { .. }
@Bean public Car mercedes() { .. }
@Bean public Car honda() { .. }
Now I can autowire all of them with:
@Autowired List<Car> cars;
With this I get all Car-objects.
Is it possible to get also the bean names somehow?
The array list can be injected using the @Autowired annotation on the spring boot. In the example below, the name list is given in the NameService class. The list is created as a spring boot bean using the @Bean annotation in the @Configuration annotation class.
Enabling @Autowired annotationSpring beans can be declared either by Java configuration or XML configuration. By declaring beans, you provide metadata to the Spring Container to return the required dependency object at runtime. This is called Spring Bean Autowiring.
Spring @Autowired Annotation - Service ClassThe setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire attribute.
In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.
M. Deinums comment had the correct solution
@Autowired Map<String, Car> carsAndNames;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With