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.
@Componentpublic 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
@Componentpublic class Customer { @Autowired private Person person;}
Setter Based
@Componentpublic class Customer { private Person person; @Autowired public void setPerson(Person person) { this.person = person; }}
Dependency Injection in @Bean
The arguments will cause the dependency injection in methods with @Bean
Following ways are possible:
Injection via Type
Injection via Name: if more than one beans are available then we can use @Qualifier() to specify the exact bean we want to inject
@Configurationpublic 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); }}