The principle of IOC (control reversal) in spring framework _IOC control inversion

Source: Internet
Author: User

I. The basic knowledge and principles of the IOC:

The background of 1.IoC theory: in the software system designed by object-oriented method, the bottom implementation is composed of N objects, and all the objects realize the business logic of the system through cooperating with each other. That is, the coupling between objects in a software system, object A and object B are related, object B is dependent on object C, so there is a complex dependency between objects and objects, so the theory of control reversal is available.



2. What is control reversal (IoC):

(1). IOC is the abbreviation of inversion of control, some translates as "inversion of controls", and translation becomes "control reverse" or "control inverted".

(2). In 1996, Michael Mattson, in an article on the exploration of object-oriented frameworks, first proposed the concept of IOC. In simple terms, the complex systems are decomposed into mutually cooperative objects, which, through encapsulation, are transparent to the outside, thereby reducing the complexity of problem solving and being flexible to reuse and extend. The point of view of the IOC theory is generally this: the decoupling of objects with dependencies by means of "third party", as shown in the following illustration:

That is, after each object class is encapsulated, the object classes are associated with the IOC container. This means that objects and objects are contacted through the IOC container, but there is no direct connection between objects and objects.

If an IOC container is removed, object A in the system has a direct relationship with Object B, as shown in the following illustration:

For example, a lot of object classes have to be associated, and it becomes complicated, as the following illustration shows:

So it is necessary to propose the inversion of IOC control.

(3). Why is this way called control reversal?

-Software system before the introduction of the IOC container, object a relies on object B, and when a object is instantiated or runs to a point, it must either actively create object B or use the object B that has been created, either by creating or using the Created object B, the control is in our own hands.

-If the software system introduces the IOC container, object A and object B lose direct contact, so when object A is instantiated and run, if object B is needed, the IOC container will actively create an object B to inject into the place needed for object A.

-Through the previous comparison, you can see that object a obtains the process of relying on object B, from the active behavior to passive behavior, that is, the creation object to the IOC container processing, control power upside down, this is the origin of control reversal.



3.IoC Alias: Dependency Injection (DI)

(1). In 2004, Martin Fowler the same question, since the IOC is a reversal of control, what is the "control that has been reversed." After detailed analysis and argument, he came to the answer: "The process of acquiring dependent objects has been reversed". After the control is reversed, the process of acquiring the dependent object becomes actively injected by the IOC container by its own management object. So he took a more appropriate name for "control reversal" called "Dependency Injection (Dependency injection,di)". His answer, in fact, gives a way to achieve the IOC: injection.

(2). The so-called dependency injection is a dynamic way of injecting a dependency into an object by the IOC container during its operation.

(3). Therefore, Dependency injection (DI) and control inversion (IoC) are the same thing that is described from different angles, that is, the decoupling between objects is realized by introducing the IoC container and using the method of dependency injection.



4. Benefits of using the IOC:

(1). Maintainability is good, very convenient for unit testing, easy to debug programs and diagnose faults. Each class in the code can be tested individually, without affecting each other, as long as it is guaranteed to function correctly, which is the benefit of low coupling or decoupling between components.

(2). The members of each development team only need to focus on the business logic they want to implement, there is no need to care about the progress of other people's work, because your task has nothing to do with others, your task can be tested alone, your task is not dependent on other people's components, no longer have to be confused about responsibility. Therefore, in a large and medium-sized projects, team members clear division of labor, responsibility is clear, it is easy to a large task divided into small tasks, development efficiency and product quality will be greatly improved.

(3). Reusability is good, we can separate common components that are commonly used, repeatedly applied to other parts of the project, or other projects, of course, this is the basic object-oriented characteristics. Obviously, the IOC has implemented this principle better and improved the reusability of modules. Implementations that conform to the interface standards can be plugged into modules that support this standard.

(4). The way in which the IOC generates objects is to go externally, that is, to define the object generation in a configuration file, so that when we replace the implementation subclass it will be very simple, as long as the configuration file is modified so that there is a full hot-swappable feature.



5.IoC principle: Control reversal is the core of the spring framework. The principle is based on the object-oriented (OO) design principles of the Hollywood Principle:don ' t call us, we'll call you (don't look for me, I'll come to you). That is, all components are passive, and all component initialization and invocation is the responsibility of the container. The component is in a container and is managed by the container. Simply put, the relationship between the container control program, rather than the traditional implementation, is controlled directly by the program code, which calls another class in a class. This is the so-called "control reversal" concept is: Control from the application code to the external container, the transfer of control, that is, the so-called reversal.



6. Factory mode:

(1). A design pattern, the factory pattern, is often used in spring IOC. The factory pattern provides an interface for creating objects.

(2). Factory mode means that when a component in an application needs the B component assistance, it is not directly instantiating the B Component object in a component, but rather through the factory of the B component, that is, the factory can generate an instance object of a type component. In this mode, a component does not need to be coupled in a hard-coded fashion with the B component, but only with the factory of the B component.

(3) The following example is attached to the previous factory model:

First, create a new Java project Factorytest, and then create a new interface animal, placed under the Com.inter package:

The Animal.java file code is as follows:

Package com.inter;

Public interface Animal {
	void Eat ();//Definition abstract eating method
	void shout ()//definition abstract called method
}


Then the new two JavaBean, namely the dog class and the cat class, placed under the Com.bean package, and all implemented the animal interface:

The Dog.java file code is as follows:

Package Com.bean;

Import Com.inter.Animal;

public class Dog implements animal{

	@Override public
	void Eat () {
		//TODO auto-generated method stub
		Sys Tem.out.println ("Dogs Eat dog Food");
	}

	@Override public
	void Shout () {
		//TODO auto-generated method stub
		System.out.println ("Barking Dog");
	}

}


The Cat.java file code is as follows:

Package Com.bean;

Import Com.inter.Animal;

public class Cat implements animal{

	@Override the public
	Void Eat () {
		//TODO auto-generated the method stub
		Syst Em.out.println ("Cat Eats cat Food");
	}

	@Override public
	void Shout () {
		//TODO auto-generated method stub
		System.out.println ("Cat meow");
	}



Then create a new factory class factory, put in Com.factory, make Dog class and cat class on the factory class, dog class and Cat class are not directly Related:

The Factory.java file code is as follows:

Package com.factory;

Import Com.bean.Cat;
Import Com.bean.Dog;
Import Com.inter.Animal;

public class Factory {public
	Animal getanimal (String name) {
		if (name.equals ("Dog")) {return
			new Dog (); C21/>}else if (Name.equals ("Cat")) {return
			new Cat ();
		} else{
			throw new IllegalArgumentException ("Incorrect parameter. ");
		}
	}
}

Finally, write a test class, put it under the Com.test package, with the following code:

Package com.test;

Import com.factory.Factory;
Import Com.inter.Animal;

public class Test {public
	static void Main (string[] args) {
		Animal a=null;
		A= (Animal) New Factory (). Getanimal ("dog");
		A.eat ();
		A.shout ();
		A= (Animal) New Factory (). Getanimal ("cat");
		A.eat ();
		A.shout ();
	}


After running, the effect is as follows:






Two. Here first introduce the basic knowledge and principles of IOC, the main components of IOC and the two ways of injection, I will write another article, lest too many people are difficult to understand, we first understand the principle of IOC. The main components of the IOC and the injection of two ways this article has been written: http://blog.csdn.net/u012561176/article/details/46006385

The above is the whole content, writing is not good, please forgive me, if there are errors, please point out, thank you.

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.