Search code examples
springdependency-injectionguice

Binding Annotation in spring


We are using guice for dependency injection. Now we want to write new project using spring boot. Since we are using Spring Boot, we think it is better to use Spring for dependency injection instead of guice.

In guice we used Binding Annoation. This is very useful if we have multiple beans available and it can be injected according the annotations.

Similar to that what we have in Spring? Do we need to name the bean accordingly and use it with @Autowire and @Qualifier?


Solution

  • You can use @Autowired when you have one bean of some type.

    @Autowired
    private MyBean myBean;
    

    For many beans example configuration class:

    @Configuration
    public class MyConfiguration {
    
     @Bean(name="myFirstBean")
     public MyBean oneBean(){
        return new MyBean();
     }
    
     @Bean(name="mySecondBean")
     public MyBean secondBean(){
        return new MyBean();
     }
    }
    

    @Autowired with @Qualifier("someName") when you have more than one bean of some type and you want some specific.

    @Autowired
    @Qualifier("myFirstBean")
    private MyBean myFirstBean;
    
    @Autowired
    @Qualifier("mySecondBean")
    private MyBean mySecondBean;
    

    When you want inject all beans of the same type you can:

    @Autowired
    private List<MyBean> myBeans;