[Java] Spring DI ③
What are you doing with DI?
- ** Find a DI managed class (component scan) **
- ** Instance creation and injection **
Component scan
- When Spring is started, the process of searching for the class with the annotation to be managed by DI runs and registers it in the DI container.
- The class managed on the DI container is called ** Bean **
[Annotation to be scanned]
- @Component
- @Controller
- @Service
- @Repository
- @Configuration
- @RestController
- @ControllAdvice
- @ManagedBean
- @Named
Instance creation and injection
- ** Instantiate and inject beans into DI container **
- Collect DI target classes (Beans) and DI creates instances of them (new)
- Inject the generated instance into the field with the following ** @ Autowired annotation **
- Field variables
- Constructor arguments
- setter argument
- You can pass an instance as an argument by prefixing the constructor with @Autowired.
- The image is "Create an instance of each class in the DI container, get the instance with getter, and call the getter of the DI container in the field with @Autowired".
//image
public class DependencyInjection{
//Create an instance of each class
private SampleComponent component = new SampleComponent();
private SampleService service = new SampleService();
//Getter for SampleComponent instance
public static SampleComponent getSampleComponent(){
return component;
}
//Getter for SampleService instance
public static SampleService getSampleService(){
return service;
}
}
- ** You can save the trouble of creating Factory class by just adding annotations such as @Component! ** **
So how do you implement it?
- Annotation base
- JavaConfig
- xml
- JavaConfig + annotation
- xml + annotation
Annotation base
- Spring automatically registers classes with @Component, @Controller, etc. in the DI container
JavaConfig
- Prepare a class with @Configuration annotation
- Prepare a getter method with @Bean annotation in the class
- The return value of getter is registered in the DI container as a bean.
- In the DI container, prepare JavaConfig class and Bean instances, and get each instance with getter at @Autowired location.
- Unlike annotation base, the return value of getter with @Bean annotation is managed by DI container.
- In other words, it is necessary to prepare methods for instances managed by DI container
- Detailed settings and switching are possible
JavaConfig + annotation
- Annotate the class you want to manage with DI such as @Controller
- Set only the instance you want to make detailed settings with JavaConfig
- If you want to create a small application based on annotations and increase the scale, or switch settings, implement it with JavaConfig + annotations.
xml based
- Do the same in xml as you set in JavaConfig