Sobes.tech
Senior

What happens at application startup if several beans match one type?

sobes.tech AI

Answer from AI

If multiple beans are suitable for injection by the same type (for example, an interface) when starting a Spring application, a conflict will occur, and the context will not be able to unambiguously select which bean to use. As a result, the application will throw a NoUniqueBeanDefinitionException.

To resolve this issue, you can:

  • Use the @Primary annotation on one of the beans to indicate the preferred one.
  • Inject the bean by name using @Qualifier.
  • Reconsider the design to avoid ambiguity.

Example:

@Component
@Primary
public class ServiceImpl1 implements MyService {}

@Component
public class ServiceImpl2 implements MyService {}

// Injection
@Autowired
private MyService myService; // will inject ServiceImpl1
What happens at application startup if several beans… - sobes.tech