Sobes.tech
Junior — Middle

How can you specify a particular Bean type in Spring using annotations for dependency injection?

sobes.tech AI

Answer from AI

In Spring, to inject a specific type of Bean when multiple candidates are available, you can use the @Qualifier annotation. It allows you to specify the name or identifier of the desired Bean to avoid ambiguity.

Example:

@Component("myBean1")
public class MyBean1 implements MyInterface { }

@Component("myBean2")
public class MyBean2 implements MyInterface { }

@Service
public class MyService {
    private final MyInterface myBean;

    public MyService(@Qualifier("myBean2") MyInterface myBean) {
        this.myBean = myBean;
    }
}

You can also use @Primary on one of the Beans to make it the default choice if @Qualifier is not specified.

How can you specify a particular Bean type in Spring… - sobes.tech