DI: What is Dependency Injection? Continued Explanation of how Spring realizes DI
Outline explanation of DI in Spring
--Reason for using DI ... I want to reduce the dependency between classes and improve reusability / testability. --How to realize ... Pass the class you want to use in a certain class with the interface type → Define the class to be actually passed separately.
--Bean ... Injection class --Bean definition ... Various properties set in the bean when injecting the bean --Bean definition file / Configuration ... A collection of Bean definitions (Java class, XML file) --DI container ... Set various beans and pass them to the other party when using them.
Next time, detailed movements of each class ApplicationContext -** The central figure in realizing DI in Java ** --A class that has the function of a DI container --A class created by extending the BeanFactory class --There is a class that is further extended by the corresponding Configuration etc. --Multiple DI containers can be created for one application
Configuration --The Bean definition file --Pass this to the ApplicationContext class and generate a bean in the DI container -There are three methods: [Java-based], [xml-based], and [annotation-based]. ――Three can be used alone, but setting becomes easier by using the annotation base and others in combination. --Write the Bean definition in this
Bean --General class, basically no special description is required If --is an annotation-based Configuration, write an annotation separately. --You can also inject and nest beans inside the bean
ex) Describe the initialization condition for the bean of HogeService in hogeConfig and get the bean via ApplicationContext (Java base)
CreateContext.java
ApplicationContext ctx = new AnnotationConfigApplicationContext(HogeConfig.class);
HogeService service = ctx.getBean(HogeService.class)
HogeConfig.java
@Configuration
public class HogeConfig {
@Bean
HogeService hogeService() {
return new HogeService();
}
}
Is it like the following when expressed in a conceptual diagram?
I think it's relatively easy to understand if you swallow the concept.
We are planning to explain the specifications etc. when actually trying it.
Recommended Posts