Dependency Injection

  • The process of injecting dependent bean objects into target bean objects is called dependency injection.

Types

  • Setter Injection: The IOC container will inject the dependent bean object into the target bean object by calling the setter method.
  • Constructor Injection: The IOC container will inject the dependent bean object into the target bean object by calling the target bean constructor.
  • Field Injection: The IOC container will inject the dependent bean object into the target bean object by Reflection API.

IoC Container

  • IoC Container is a framework for implementing automatic dependency injection.
  • It manages object creation and its life-time and also injects dependencies into the class.
  • ApplicationContext wraps the BeanFactory which serves the beans to the runtime of the application
  • Spring Boot provides auto-configuration of application context

@Autowired

Constructor Based

  • If a class, which is configured as a Spring bean (for example @Component, has only one constructor, the @Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
@Component 
public class Customer {
    private Person person;
 
    public Customer() {
    }
 
	// can be ommitted since class is a bean and there is single constructor
    @Autowired 
    public Customer(Person person) {
        this.person = person;
    }
}

Property Based

@Component
public class Customer {
    @Autowired
    private Person person;
}

Setter Based

@Component
public class Customer {
	private Person person;
	
	@Autowired
	public void setPerson(Person person) {
	    this.person = person;
	}
}

Dependency Injection in @Bean

@Configuration
public class Config {
    // creating bean just for example
    // name of the bean will be "bean1"
    @Bean
    public BeanA bean1() {
        return new BeanA();
    }
 
    // Injecting via type "BeanA"
    @Bean
    public BeanB bean2(BeanA theBean) {
        return new BeanB(theBean);
    }
 
    // Injecting via name "bean1"
    @Bean
    public BeanB bean3(@Qualifier("bean1") BeanA theBean) {
        return new BeanB(theBean);
    }
}