Control inversion (IoC) vs. Dependency Injection (DI)

Source: Internet
Author: User

Original: 1. Control Reversal (inversion of Control) and Dependency Injection (Dependency injection)Control inversion, the IOC (inversion of control), gives the container the right to assemble and manage object components by means of a container, by handing over the call of objects that are traditionally manipulated directly by the program code. The so-called "inversion of Control" concept is the transfer of control over a Component object, from the program code itself to the external container. The IOC is a big concept that can be implemented in different ways. There are two main implementations of:<1> dependent lookup (Dependency lookup): ContainerProvides a callback interface and context for Components。 Both EJB and Apache Avalon Use this approach. <2> Dependency Injection (Dependency injection): The component does not do a location query, only provides a common Java method for the container to determine the dependency relationship. The latter is the most popular type of IOC nowadays, and it has interface injection (Interface injection), set value injection (Setter injection) and construction sub-injection (Constructor injection) three ways. Figure 1 Control inversion conceptual structure Dependency injection is more prevalent because it is a preferable way: to let the container take full responsibility for dependent queries, the managed component only needs to expose the JavaBean setter method or the constructor or interface with parameters, so that the container can be assembled at initialization Objectof dependency relationships. The main advantage is that the:<1> find-and-locate operation is completely unrelated to the application code, compared to the dependent lookup method. <2> does not depend on the container's API, it is easy to use the Application object outside any container. <3> does not require a special interface, and most objects do not have to rely on containers at all. 2. Hollywood PrinciplesThe IOC embodies the Hollywood principle that "don't call, we'll call you." The first time I met the Hollywood principle is that when you understand the template Mathod pattern, the core of the template method pattern is that the base class (abstract class) defines the skeleton of the algorithm, and some steps are deferred to the subclass. Figure 2 Template method pattern class diagram now to consider the IOC implementation mechanism, the component defines the entire process framework, and some of the business logic implementation to rely on the addition of other business objects, they can participate in the business process in two ways, one is dependent on lookup (Dependency lookup), Similar to the implementation of JDNI, the corresponding business object (code 1) is found through Jndi, and the other is dependency injection, which injects the business object into the component through the IOC container. 3. Dependent Lookups ( Dependency Lookup )The following code shows the dependency lookup mechanism based on the JNDI implementation.
public class mybusniessobject{private DataSource ds;   Private Mycollaborator Mycollaborator;    Public Mybusnissobject () {Context CTX = null;try{CTX = new InitialContext ();    ds = (DataSource) ctx.lookup ("Java:comp/env/datasourcename");    Mycollaborator = (mycollaborator) ctx.lookup ("Java:comp/env/mycollaboratorname"); }......
Code 1 Dependency lookup (Dependency Lookup) code The main problem with dependency lookups is that this code must depend on the JNDI environment, so it cannot run outside the application server, and if you want to replace Jndi in other ways to find resources and collaboration objects, The Jndi code must be pulled out to refactor into a strategy approach. 4. Dependency Injection ( Dependency Injection )The basic principle of dependency injection is that the application component should not be responsible for locating resources or other dependent collaboration objects. The work of the configuration object should be the responsibility of the IOC container, and the logic for "find resources" should be taken from the code of the application component and given to the IOC container. The following shows the injection mechanism in 3 respectively. Code 2 business object to be injected
Package com.zj.ioc.di;  Public class Content { public void busniesscontent () {System.     out. println ("does business"); } public void anotherbusniesscontent () {System.     out. println ("Does another Business"); }}
The Mybusniess class shows a business component whose implementation requires the injection of object content. Code 3, Code 4, code 5,6 demonstrates the construction of sub-injection (Constructor injection), set value injection (Setter injection) and interface injection (Interface injection) three ways.   Code 3 Construction sub-injection (Constructor injection)
package  com.zj.ioc.di.ctor; import  com.zj.ioc.di.content;  public   class  mybusiness {     private  Content myContent;       public  mybusiness (content content) {        mycontent = content;    }        Public   void  dobusiness () {        Mycontent.busniesscontent ();     }        Public   void  doanotherbusiness () {        Mycontent.anotherbusniesscontent ();     }}
  Code 4 setpoint injection (Setter injection)
Package com.zj.ioc.di.set; import com.zj.ioc.di.Content;  Public class     mybusiness { private Content mycontent;  Public    void setcontent (content content) {mycontent = content;    } public void dobusiness () {mycontent.busniesscontent ();    } public void doanotherbusiness () {mycontent.anotherbusniesscontent (); }}
Code 5 Setting the injection interface
Package com.zj.ioc.di.iface; import com.zj.ioc.di.Content;  Public Interface incontent { void createcontent (content content);}
Code 6 Interface Injection (Interface injection)
package  com.zj.ioc.di.iface; Import  com.zj.ioc.di.content;  public   class   mybusiness  implements  incontent{     Private  content mycontent;      public   void  createcontent (content content) {       mycontent = content;     }        public   void  dobusniess () {       mycontent.busniesscontent ();     }        public   void  doanotherbusniess () {       mycontent.anotherbusniesscontent ();     }}
5. rely on drag and drop (Dependency pull)The last thing you need to introduce is the dependency drag-and-drop, how the injected object relates to the component, and the process is implemented by relying on drag and drop. Code 7 Dependency Drag-and-drop example
public static void Main (string[] args) throws Exception{//get the bean factorybeanfactory factory = Getbeanfactory (); Messagerender Mr = (Messagerender) factory.getbean ("renderer"); Mr.render ();}
Typically, the configuration of the injected object can be done through an XML file. Using this approach to manage objects centrally, the difference between using dependency drag and dependency lookup is that dependent lookups are performed in business component code, not from a centralized registry, a specific location.

Control inversion (IoC) vs. Dependency Injection (DI)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.