Junior — Middle
How is a specific Bean implementation selected during application runtime in Spring?
sobes.tech AI
Answer from AI
In Spring, the specific Bean implementation is selected using the dependency injection mechanism. If multiple implementations of an interface or class are defined in the application context, Spring uses the following approaches to choose the needed Bean:
- By Bean name: specify the exact Bean name using the
@Qualifierannotation. - By annotations: e.g.,
@Primarymarks a Bean as preferred during autowiring. - By type: if only one implementation exists, Spring automatically chooses it.
Example using @Qualifier:
@Component
public class ServiceImpl1 implements MyService { ... }
@Component
public class ServiceImpl2 implements MyService { ... }
@Component
public class Consumer {
private final MyService myService;
@Autowired
public Consumer(@Qualifier("serviceImpl1") MyService myService) {
this.myService = myService;
}
}
If @Qualifier is not specified and multiple implementations exist, Spring will throw an exception due to ambiguity. Using @Primary on one Bean makes it the default choice.