Spring (3)------control inversion (IOC)/Dependency Injection (DI)

Source: Internet
Author: User

One. Spring Core Concept Understanding

Control inversion:

Control inversion is IOC (inversion of control). It gives the container the right to call the object that is traditionally manipulated directly by the program code. Implements assembly and management of object components through containers.

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.


There is no control to invert such a pattern before. You create an object. Where to use. You have to go through the keywordnew alone.

But now it is not possible to give the new object the right to the spring configuration file. Using the config file to ' new ',

Is the reversal of power. What you have done is now handed over to others.



The IOC is a very large concept that can be implemented in different ways.


There are two main ways of achieving this:
(1) Dependent lookup (Dependency lookup): The container provides the callback interface and context to the component .
(2) Dependency Injection (Dependency injection): The component does not do the location query, only provides the common Java method to let the container decide the dependency relationship.
The latter is the most popular type of IOC nowadays, and it has interface injection (Interface injection). There are three ways to set value injection (Setter injection) and construct sub-injection (Constructor injection).



What exactly is the relationship between control inversion and dependency injection?
Control inversion is a pattern, is a big concept, and the most detailed explanation of control inversion is the dependency injection, the former is to say a large range,
The latter is detailed to the substance of this matter.

Just like your friend said that you must give a gift for your birthday, and so on your birthday, I gave you a cell phone,
Giving presents is a big concept, like controlling inversion. The detailed delivery of a mobile phone, is dependent on injection. But the two show that the gift is the thing.
Of course, there are three ways to rely on injection, just like your friend can choose to send you an Apple phone or send you a BMW or send you a villa three ways to inject,
Probability is not necessary to understand the semantics, the car will be opened first. Slowly you will know how the car is composed.


Ii. understanding of the IOC conceptual example

In writing a program. There are many implementations in the way that you assume each time by changing the program code. With new to achieve different functions, the coupling is too high,

The IOC was born to solve loose coupling. This is understood by code.

(1) Creating interfaces and implementing classes

Interface:

Package Com.lanhuigu.spring.impl;public interface Isayhello {/** * speak different languages * @return */public String Dosay ();}

Chinese-Speaking implementation class:

Package Com.lanhuigu.spring.impl;public class Chhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * Speak Chinese * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "Chinese:" +MSG;}}

English-Speaking implementation class:

Package Com.lanhuigu.spring.impl;public class Enhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * * Speak English * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "English:" +MSG;}}

(2) Configuring the spring file

Package Com.lanhuigu.spring.impl;public class Enhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * * Speak English * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "English:" +MSG;}}

(3) test procedure

Package Com.lanhuigu.spring.test;import Org.junit.test;import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.lanhuigu.spring.impl.isayhello;public class Testhelloworld {@Testpublic void Testmyhelloworld () {//1. Read spring-initialized configuration file ApplicationContext acxt = new Classpathxmlapplicationcontext ("/applicationcontext.xml");//2. The Isayhello implementation class object Isayhello SayHello = (Isayhello) acxt.getbean ("SayHello") is obtained from the Bean,//3. Calling interface Methods System.out.println ( Sayhello.dosay ());}}
The example of IOC is realized by the above code:

(1) In the test procedure, assuming that the IOC is not used, you can use new to realize what language to speak

Isayhello SayHello = new Chhelloimpl ();//Speak Chinese

Isayhello SayHello = new Enhelloimpl ();//English speaking

Maybe think I will be able to new, leadership let me speak English, I will speak English. The leader wants me to speak Chinese, I will speak Chinese, I can stare back and forth,

But. Assuming that there are 10,000 places in an application that use this code, do you have to stare at 10,000 places and have absolutely 100,000 of your heart dissatisfied with the leader. Change to get sick!

You may not be satisfied. I just stare at 10,000 places, assuming there are 1 million places, you are not 1 million ' grass mud horse ' on the Prairie Pentium Ah!


This time the IOC to solve the problem for you, a dose of medicine can be cured, no longer worry about the leadership let you say what you do not have to say.

Control what language to speak through the configuration file:

<bean id= "SayHello" class= "Com.lanhuigu.spring.impl.ChHelloImpl" >
<!--to inject variable msg-value dependency
<property name= "MSG" >
<value> Test </value>
</property>
</bean>

Your profile allows you to say anything by implementing a class configuration. Class= "Com.lanhuigu.spring.impl.ChHelloImpl",

And the application code is unaffected:

Isayhello SayHello = (Isayhello) acxt.getbean ("SayHello");

System.out.println (Sayhello.dosay ());

The application simply gets what the bean object is. I will say what, as for your container how to configure. Application Not dick you,

The container then configures its own implementation class. As for what your application does. The container is no matter. Through this relationship

Realize the effect of low coupling and realize the function of inversion of control.

Three, Dependency injection (DI)

Implications of Dependency Injection:

Let the primary key depend on abstraction, and when the component is going to have relationships with other real objects, it injects the actual object of the dependency through the abstraction.

The three implementations of dependency injection are respectively interface injection (interface injection), set method injection (setter injection). Construction injection (constructor injection).

(1) Interface Injection (interface injection):

Define an interface that will be English:

Package Com.lanhuigu.spring.impl;public interface Isayhello {/** * speak English * @return */public String dosay (Enhelloimpl en);}
English-speaking interface implementation class:

Package Com.lanhuigu.spring.impl;public class Enhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * * Speak English * * @Overridepublic String Dosay (Enhelloimpl en) {//TODO auto-generated method Stubreturn "English:" +MSG;}}
Assume that the interface is injected in a way. The interface, which can speak various languages, is defined as an English-speaking interface only. The entire business logic class relies on this interface.

In spring, interface injection is defined when the IOC concept is not established, and now spring does not recommend interface injection, the interface injection business logic class depends on the interface, not the focus.

(2) Set method injection (setter injection):

Set injection is the definition of a set method in a class that accepts injections, and defines the number of parameters that need to be injected in the parameters.

In order to be able to inject multiple languages, the interface injection method is not applicable, we define the interface as open. So that every implementation of the class based on need to do their own

Business logic, passing in the parameters through the set method.

Interface:

Package Com.lanhuigu.spring.impl;public interface Isayhello {/** * speak different languages * @return */public String Dosay ();}

Implementation class:

Chinese implementation class:

Package Com.lanhuigu.spring.impl;public class Chhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * Speak Chinese * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "Chinese:" +MSG;}}

English Implementation class:

Package Com.lanhuigu.spring.impl;public class Enhelloimpl implements Isayhello {private string Msg;public string getmsg ( ) {return msg;} public void Setmsg (String msg) {this.msg = msg;} /** * * Speak English * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "English:" +MSG;}}
Configuration file Incoming parameters:

<?xml version= "1.0" encoding= "UTF-8"?><!---Application context definition for Jpetstore's business layer.  -Contains bean references to the transaction manager and to the DAOs in-dataaccesscontext-local/jta.xml (see web. xml)  "Contextconfiglocation"). --><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:tx="/HTTP/ Www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPRING-BEANS-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-2.5.xsd "><!--defines a bean with ID SayHello, which implements the class through the Spring configuration file transformation. Implement different functions, no need to change other programs--><bean id= "SayHello" class= "Com.lanhuigu.spring.impl.ChHelloImpl" ><!--to inject the variable msg value dependency- -><prOperty name= "msg" ><value> test </value></property></bean></beans> 
Each interface implementation class corresponds to a logic that the spring configuration file is responsible for leveling.

The property of the profile bean has a default property name, and this name corresponds to the attribute name msg in the Bean's class class object.

Code style Private String Msg,value is the property value, through the set method in the class, the property value in the configuration file is injected,

Gets the property value in the class by get.


(3) Construction Injection (constructor injection):

Construct injection is the definition of a constructor in a class that accepts injections, and defines the elements that need to be injected in the parameters.

Let's change the English language into a construction method to inject:

Interface:

Package Com.lanhuigu.spring.impl;public interface Isayhello {/** * speak different languages * @return */public String Dosay ();}
Implementation class:

Package Com.lanhuigu.spring.impl;public class Chhelloimpl implements Isayhello {private string Msg;private string two;/* * * Construction Method injected * @param msg * @param */public Chhelloimpl (String msg,string) {this.msg = Msg;this.two = both;} /*public String getmsg () {return msg;} public void Setmsg (String msg) {this.msg = msg;} *//** * Speak Chinese * * @Overridepublic String Dosay () {//TODO auto-generated method Stubreturn "Chinese:" +msg+two;}}
Spring configuration file:

<?

XML version= "1.0" encoding= "UTF-8"?

><!---Application context definition for Jpetstore's business layer. -Contains bean references to the transaction manager and to the DAOs in-dataaccesscontext-local/jta.xml (see web. xml) "Contextconfiglocation"). --><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:tx="/HTTP/ Www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPRING-BEANS-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-2.5.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-2.5.xsd "><!--defines a bean with ID SayHello, implements the class through the Spring configuration file transformation, implements different functions, No need to change other programs--><bean id= "SayHello" class= "Com.lanhuigu.spring.impl.ChHelloImpl" ><!--to inject variable msg value dependency <!--<property name= "MSG" &GT;&LT;VALUE&Gt; test </value></property>--><!--constructs into injection, assuming that no index is written, the default constructor method has only one parameter, assuming that multiple injections are injected. If you inject multiple parameters, you can specify the corresponding relationship with the construction method parameters by index subscript, the subscript starts at 0, 0 represents the first parameter of the construction method, and so on--><constructor-arg index= "0" >< value> test </value></constructor-arg><constructor-arg index= "1" ><value>two Arg</value ></constructor-arg></bean></beans>

Test procedure:

Package Com.lanhuigu.spring.test;import Org.junit.test;import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.lanhuigu.spring.impl.isayhello;public class Testhelloworld {@Testpublic void Testmyhelloworld () {//1. Read spring-initialized configuration file ApplicationContext acxt = new Classpathxmlapplicationcontext ("/applicationcontext.xml");//2. The Isayhello implementation class object Isayhello SayHello = (Isayhello) acxt.getbean ("SayHello") is obtained from the Bean,//3. Calling interface Methods System.out.println ( Sayhello.dosay ());}}
Output Result:

English: Test both ARG

Note points for constructing method injection:

(1) The number of references to be injected in the constructed method of receiving the injection

(2) The configuration file constructs the attribute Constructor-arg does not write the index when the default one parameter, assumes constructs the method to have several parameters, will error

(3) Assume that multiple parameters are injected. In the configuration file, Constructor-arg through the index to understand the value of the corresponding construction method of the number of parameters

Four. Summarize

There are three kinds of injection methods for dependency injection, which is the best way to inject. It is generally recommended to use set injection

Interface injection is not considered. Construction method injection through the above example can be seen, assuming that the injection of too many parameters,

In the construction method there will be a bunch of parameters, looking at the confusion, and the spring configuration file also has to do the corresponding value of the parameters,

Suppose there are too many injected classes and too many parameters. The more you configure the constructor, the more confused you will be.

The set is based on the name injection, you can avoid the construction method injection trouble. However, using the Set method injection is a dynamic injection parameter.

may have been tampered with. The construction method injection is complete when the class is started, and there is no possibility of tampering. relatively high security. Each has

Future generations. But the pass often uses set injection. The construction method injects discretion.

To inject, which is better than the construction method.


Spring (3)------control inversion (IOC)/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: 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.