(This article is from the dream storm blog)
A friend sent a mail to ask a few questions, one of which is about IOC and Di:
What is the relationship between inversion of control and dependency injection? I think the two words represent the same meaning, but only two different representations, right?
Below are some of my understandings of this issue.
To be accurate, IOC and Di are different, which can be seen literally. Otherwise, they can be called a name. Pai_^
To understand IOC, we need to know what control is and how it is replaced by inversion. In fact, IOC is used to describe"ProgramThe best evidence of the differences between libraries and frameworks. When using the library, the control is in our hands, and we writeCodeCall the implementation of the library to complete the corresponding functions. Think about how we use JDK. When using the framework, control is in the hands of the Framework. Our code is ultimately called by the framework. A common example is servlet, the servlet code we compiled is placed in the entire servlet framework and called by the Web container. This is the difference. We are more accustomed to controlling everything on our own. Therefore, we use "inversion" to describe how to control the framework. This is what Martin Fowler named Di in that article.ArticleAll frameworks are the cause of IOC.
The core container of spring is a framework, so we can say it is IOC, but as mentioned above, every framework has IOC, so simply using IOC is not enough to explain everything. Spring core containers assemble components, which is the most significant difference from other common frameworks. If IOC is used to describe the framework, the control mentioned here is actually the assembly process of components.
From the perspective of spring core containers, the assembly process is to install the components on which the components depend. From the perspective of a single component, the components required by the component are installed externally, this process is like putting the "dependency" potion into the body of the component with the syringe "injection", so we call it "dependency injection ".
The container that completes component assembly is not just a form of injection, but also a common method is "dependency lookup", that is, each component finds its own content. There are also different implementation methods as to where to find them, such as fixing them to a certain place (such as using static methods), and injecting search points into them through di.
Martin Fowler's article has clearly explained the concepts of IOC and Di. We only need to savor them.