Spring entry-control inversion (IOC) and dependency injection (DI), springioc

Source: Internet
Author: User
Tags ip number

Spring entry-control inversion (IOC) and dependency injection (DI), springioc

1. Inversion of Control and Dependency Injection)

Control Inversion is IoC (Inversion of Control). It gives the call permission of objects that are traditionally directly controlled by program code to containers, and uses containers to assemble and manage object components. The so-called "control inversion" concept is the transfer of control over the component object, from the program code itself to the external container.


IoC is a big concept and can be implemented in different ways. There are two main implementation methods: <1> Dependency Lookup: The container provides the callback interface and context to the component. This method is used by both EJB and Apache aveon. <2> Dependency Injection: The component does not locate the query, but only provides a common Java method for the container to determine the Dependency. The latter is the most popular IoC type. It has three methods: Interface Injection, Setter Injection, and Constructor Injection.


Figure 1 concept structure of control reversal

Dependency injection is more popular because it is a more desirable method: the container is solely responsible for dependency queries. The managed component only needs to expose the setter method of the JavaBean or a constructor or interface with parameters, this allows containers to assemble object dependencies during initialization. Compared with the dependency search method, this method has the following advantages: <1> the search and positioning operation has nothing to do with the application code. <2> container-independent APIs allow you to easily use application objects outside any container. <3> no special interfaces are required. Most objects do not need to depend on containers at all.
 
2. Hollywood principles
IoC embodies the Hollywood principle: "Don't call us, we will call you ". The first time I met the Hollywood principle was to understand the Template method (Template Mathod) mode, the core of the Template method mode was that the base class (abstract class) defined the skeleton of the algorithm, and delay some steps to the subclass.


Now let's take into account the implementation mechanism of IoC. components Define the entire process framework, and the implementation of some business logic needs to be added by adding other business objects, they can be involved in the business process in two ways. One is Dependency Lookup. Similar to JDNI implementation, the corresponding business object (Code 1) can be found through JNDI ), the other is dependency injection, which injects business objects into components through the IoC container.

3. Dependency Lookup)
The following code demonstrates the dependency Search Mechanism Based on JNDI.

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”);    }……

The main problem with dependency lookup is that this code must be dependent on the JNDI environment, so it cannot run outside the application server. If you want to replace JNDI with other methods to find resources and collaboration objects, the JNDI code must be extracted and reconstructed into a policy method.

4. Dependency Injection)
The basic principle of dependency injection is that application components should not be responsible for searching resources or other dependent collaboration objects. The IoC container is responsible for the configuration object. The logic of "Search for resources" should be extracted from the code of the Application Component and handed over to the IoC container.
The following shows the injection mechanism in step 3.
Code 2 business object to be injected Content. java

package com.zj.ioc.di; public class Content {     public void BusniessContent(){       System.out.println("do business");    }       public void AnotherBusniessContent(){       System.out.println("do another business");    }}

The MyBusniess class shows a business component whose implementation requires object Content injection. Code 3, code 4, Code 5, and 6 demonstrate three methods: Constructor Injection, Setter Injection, and Interface Injection.
 
Code 3 Constructor Injection MyBusiness. java

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 Setter Injection MyBusiness. java

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 sets the InContent. java 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 MyBusiness. java

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();    }}

The above is the basic understanding of spring, but it takes a small step to understand spring. The true understanding should be put in practice.


What does IoC/dependency injection (DI) in Spring mean? Is the name different? Which one is in Spring 3?

The content of the same thing is different. IoC controls inversion, emphasizing the role of the container and is used to organize or control the bean running in the container. DI dependency injection. It is emphasized that the Bean needs external injection for normal operation. Comparatively speaking, the container framework (such as Spring) emphasizes control and how to better control the running of other beans. On the contrary, the module emphasizes injection, what exactly do I need dependency injection.
In essence, the main advantage is to decouple through interfaces, and then use the container configuration file to organize bean operation, which is more scalable and can be flexibly used for Large-scale Module and component-level programming. Spring is already a mature container framework. Therefore, most people mainly consider what dependency injection is required.

Implement control inversion and dependency injection in spring

IoC and DI
First, I want to talk about IoC (Inversion of Control, Control reversal ). This is the core of spring. For the spring framework, the so-called IoC is that spring is responsible for controlling the relationship between object lifecycles and objects. What does this mean? For example, how do we find a girlfriend? The common situation is that we go around to see where there is a beautiful and good mm, and then inquire about their interests, QQ number, phone number, ip number, iq number ........., Find a way to get to know them and give them what they want ...... This process is complex and profound, and we must design and face each link on our own. This is also true for traditional program development. To use another object in an object, you must obtain it (new by yourself or query one from JNDI ), after use, the object will be destroyed (such as Connection), and the object will always be combined with other interfaces or classes.
How does IoC work? It's a bit like finding a girlfriend through a matchmaking agency. I introduced a third party between my girlfriend and me: the marriage agency. The matchmaking agency manages a lot of information about men and women. I can submit a list to the matchmaking agency to tell it what kind of girlfriend I want to find, such as Li jiaxin, Lin xilei, and Jay Chou, the speed is like Carlos, the technology is like Zidane, and then the matchmaking agency will provide a mm according to our requirements. We just need to get in love with her and get married. It is simple and clear. If the person selected by the matchmaking agency does not meet the requirements, we will throw an exception. The entire process is no longer controlled by myself, but controlled by a mechanism similar to a container such as matchmaking agency. This is the development method advocated by Spring. All classes will be registered in the spring container to tell spring what you are and what you need, then spring will take the initiative to give you what you want when the system runs properly, and also give you something else you need. The creation and destruction of all classes are controlled by spring. That is to say, the object lifecycle is not referenced but spring. For a specific object, it used to control other objects. Now all objects are controlled by spring, so this is called control inversion. If you still don't understand, I decided to give up.
IoC dynamically provides other objects required by an object during system running. This is achieved through DI (Dependency Injection, Dependency Injection. For example, object A needs to operate the database. In the past, we always had to write code in A to obtain A Connection object. With spring, we only need to tell spring that A Connection is required in, as for how to construct the Connection and when to construct it, A does not need to know. When the system is running, spring will create A Connection at an appropriate time and inject it into A like an injection. This completes the control of the relationship between objects. A needs to rely on the Connection to run normally, and the Connection is injected into A by spring, so the dependency injection name is like this. How is DI implemented? A major feature after Java 1.3 is reflection, which allows programs to dynamically generate objects, execute object methods, and change object attributes during runtime, spring is injected through reflection. For more information about reflection, see java doc.
After understanding the concepts of IoC and DI, everything will become simple and clear, and the rest of the work is just accumulating wood in the spring framework.

If you still don't understand, give up java!

Let's take a look at how Spring runs.

Java code

Public static void main (String [] args ){
ApplicationContext context = new FileSystemXmlApplicationContext (
... The remaining full text>
 

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: info-contact@alibabacloud.com 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.