Spring Autowire
Autowiring feature enables you to inject the object dependency implicitly.
Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a spring configuration file, Spring container can qutowire relationships between collaborating beans.
Once you enable annotation, we can use autowiring on properties, setters and constructors.
on Properties
Step1: Define Bean
@component("tempComponent)
public class TempComponent {
public String format(){
return "Temp";
}
}
Step2: we will inject above bean into below service using @Autowire on the field definition
@component
public class TempService {
@Autowire
private TemoComponent tempComponent;
}
on Setters
Step1: Define Bean
@component("tempComponent)
public class TempComponent {
public String format(){
return "Temp";
}
}
Step2: we will inject above bean into below service using @Autowire on a setter method.
@component
public class TempService {
private TemoComponent tempComponent;
@Autowired
public void setTempComponent(TempComponent tempComponent){
this.tempComponent = tempComponent;
}
}
on Constructors
Step1: Define Bean
@component("tempComponent)
public class TempComponent {
public String format(){
return "Temp";
}
}
Step2: we will inject above bean into below service using @Autowire on the constructor.
@component
public class TempService {
private TemoComponent tempComponent;
@Autowired
public TempService(TempComponent tempComponent){
this.tempComponent = tempComponent;
}
}
note
By default Spring resolves @Autowired entries byType. If more than one bean of the same type is available in the container, the framework will throw fatal exception
To resolve this conflict, we need to tell spring explicitly which bean we want to inject. we can do it in 3 ways.
- Autowiring by Qualfier
- Autowiring by Custom Qualifier
- Autowiring by Name