Autowiring Dependencies

From OasisSoftTech.com - Knowledge Base/Java/Springframework/Microservices/Cloud-AWS/AI
Jump to: navigation, search

Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined.

There are four modes of autowiring a bean using an XML configuration:

  • no: the default value – this means no autowiring is used for the bean and we have to explicitly name the dependencies
  • byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set
  • byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there’s more than one bean of that type, the framework throws an exception.
  • constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments

For example, let’s autowire the item1 bean defined above by type into the store bean:

@Bean(autowire = Autowire.BY_TYPE)
public class Store {
     
    private Item item;
 
    public setItem(Item item){
        this.item = item;    
    }
}

We can also inject beans using the @Autowired annotation for autowiring by type:

public class Store {
     
    @Autowired
    private Item item;
}


If there’s more than one bean of the same type, we can use the @Qualifier annotation to reference a bean by name:

public class Store {
     
    @Autowired
    @Qualifier("item1")
    private Item item;
}

Now, let’s autowire beans by type through XML configuration:

<bean id="store" class="org.baeldung.store.Store" autowire="byType"> </bean>

Next, let’s inject a bean named item into the item property of store bean by name through XML:

<bean id="item" class="org.baeldung.store.ItemImpl1" />
 
<bean id="store" class="org.baeldung.store.Store" autowire="byName">
</bean>


We can also override the autowiring by defining dependencies explicitly through constructor arguments or setters.