Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire list of Beans in Spring an get their names

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?

like image 304
Marcel Avatar asked Jun 07 '16 07:06

Marcel


People also ask

Can you Autowire a list?

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.

How do I get Autowired beans?

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.

Does Spring @autowired inject beans by name or by type?

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.

How do I list beans in Spring boot?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.


1 Answers

M. Deinums comment had the correct solution

@Autowired Map<String, Car> carsAndNames;
like image 164
Marcel Avatar answered Oct 28 '22 20:10

Marcel