Sobes.tech
Junior — Middle

How to select a specific bean implementation when registering new instances with the same type in a library?

sobes.tech AI

Answer from AI

In Java, when using dependency injection libraries (such as Spring), it is possible to register multiple beans of the same type but with different names or annotations. To select a specific implementation during injection, the following are used:

  • Named beans: when registering a bean, a name is specified, and during injection, the @Qualifier annotation with this name is used.
  • Custom annotations: create custom annotations to mark beans and use them during injection.

Example using @Qualifier:

@Component("serviceA")
public class ServiceA implements MyService {}

@Component("serviceB")
public class ServiceB implements MyService {}

@Autowired
@Qualifier("serviceB")
private MyService myService;

Thus, it is possible to explicitly specify which bean to inject if there are multiple implementations of the same interface.

How to select a specific bean implementation when… - sobes.tech