Sobes.tech
Junior — Middle

What actions do you take if multiple beans of the same class are found in the Spring container?

sobes.tech AI

Answer from AI

If multiple beans of the same class are found in the Spring container and a specific bean needs to be injected, the following actions can be taken:

  • Use the @Qualifier annotation together with @Autowired to explicitly specify the name of the desired bean.
  • Assign the @Primary annotation to one of the beans so that Spring chooses it by default during autowiring.
  • Inject the bean by name through XML configuration or via a constructor with parameters.

Example with @Qualifier:

@Autowired
@Qualifier("beanName")
private MyClass myBean;

This helps avoid ambiguity when there are multiple beans of the same type.