Junior — Middle
How to determine a specific Bean for dependency injection based on context?
sobes.tech AI
Answer from AI
In Java, especially within the Spring Framework, there are several approaches to select a specific Bean for injection depending on the context:
- @Qualifier annotation — explicitly specifies which Bean to inject when there are multiple candidates.
@Autowired
@Qualifier("beanName")
private MyService myService;
- Using profiles (@Profile) — Beans are activated only under certain application profiles.
@Profile("dev")
@Component
public class DevDataSource implements DataSource { ... }
-
Configuration via parameters or conditions (@Conditional) — Bean is created when certain conditions are met.
-
Constructor injection with parameters — different implementations can be passed depending on the context.
Thus, the choice of a specific Bean depends on the settings and annotations that manage the application context and configuration.