"SSH series" three kinds of dependency injection methods in the spring IOC

Source: Internet
Author: User

The core idea of spring is that the IOC and aop,ioc-control inversion is an important object-oriented programming law to reduce the coupling problem of computer programs, and control inversion is generally divided into two types, dependency injection and dependency lookup, what depends on? Why do I need to rely? Inject what? Control what? is dependency injection and control inversion the same concept? Contact with new knowledge, small part of the head is a big question mark, but no matter, today's blog, small series mainly to briefly introduce the spring IOC in the method of dependency injection.
Dependency injection and control inversion are designed to decouple classes from classes and improve the scalability and maintainability of the system. We can understand from the following aspects:
A, who are the participants?
B, dependence: Who depends on who? Why do I need to rely?
C, inject: who injects who? And what did it inject?
D, control reversal: who Controls who? Control what? Why is it called inversion? Is there a positive turn?

E, control inversion and dependency injection are the same concepts? We need to understand the above problem, which is helpful for the understanding of control inversion and dependency injection.

first of all: first question, who are the participants?
1) Object
2) Ioc/di Container
3) external resources for an object
second question: Dependence, who depends on who? Why do I need to rely?
Dependence, well understood, the object depends on the Ioc/di container, as for why to rely on it? Objects need to ioc/di containers to provide the external resources required by the object.
The third question: inject, who injects who? And what did it inject?
It is obvious that the Ioc/di container is injected into the object and what is injected? It's definitely injected with something that needs to be injected with the resources that are needed to inject the object, and certainly not to inject irrelevant content, you say?
question fourth: control reversal, who controls who? Control what? Why is it called inversion? Is there a positive turn?
Control inversion, control what? Must be Ioc/di container control object, mainly control object instance creation, inversion is relative to the positive, then what is positive? Consider the general application, what would you do if you were to use C in a? Of course, it is directly to create a C object, that is, in class A to take the initiative to obtain the required external resource C, this situation is called forward. So what's the reverse? Is that class A no longer takes the initiative to acquire C, but passively waits, waits for the Ioc/di container to get an instance of C, and then injects the reverse into Class A.
question fifth: is the same concept of control inversion and dependency injection?
Dependency injection and control inversion are different descriptions of the same thing, and in one way or another, they describe different angles. Dependency injection is described from an application perspective, where dependency injection can be described as the complete point: The application relies on the container to create and inject the external resources it needs, while control inversion is described from the container's perspective, describing the complete point: container control applications, the external resources required by the container to inject the application into the application in reverse.

Understanding these basic concepts, figuring out the connections and differences between them, can help us understand better, and then we'll focus on dependency injection, and there are three dependency injections in the spring IOC, namely:
A, interface injection;
B, setter method injection;
C, construction method injection;
Then the small part of the three kinds of injection methods to explain, through the demo, hope to help small partners better understanding, shortcomings also please advice.
Interface Injection

public class ClassA {  private interfaceb clzb;  public void DoSomething () {    Ojbect obj = Class.forName (config.bimplementation). newinstance ();    CLZB = (interfaceb) obj;    Clzb.doit ();   } ......}
explaining the Code section above, ClassA relies on the implementation of INTERFACEB, how do we get the implementation instance of INTERFACEB? The traditional approach is to create an instance of the INTERFACEB implementation class in your code and give clzb. This way, ClassA relies on the implementation of INTERFACEB at compile time. In order to separate the caller from the implementation at compile time, the above code is available. We dynamically load the implementation class based on the class name (config.bimplementation) of the implementation class set up in the configuration file, and use it for ClassA after Interfaceb forced transformation, which is the most primitive prototype of interface injection.

Setter Method Injection

Setter Injection mode has a very wide application in the actual development, the setter method is more intuitive, we look at the spring configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmln           S: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-4.1.xsd http://www.springframework.org/schema/a Op http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http: Www.springframework.org/schema/tx/spring-tx-4.1.xsd "> <!--Using spring to manage object creation, and object dependencies--<bean I D= "Userdao4mysql" class= "Com.tgb.spring.dao.UserDao4MysqlImpl"/> <bean id= "userdao4oracle" class= "com.tgb.sp          Ring.dao.UserDao4OracleImpl "/> <bean id=" Usermanager "class=" Com.tgb.spring.manager.UserManagerImpl "> <!--(1) usermAnager uses USERDAO,IOC to automatically create the appropriate Userdao implementations, all of which are managed by the container-<!--(2) to provide constructors in Usermanager, so that spring will inject Userdao implementation (DI) over--&G          T <!--(3) Let spring manage the creation and dependency of our objects, we must configure the dependencies to spring's core configuration file--<property name= "Userdao" ref= "Userdao4oracl   E "></property> </bean> </beans>
then let's take a look at the setter representing the way the dependency is written

Import Com.tgb.spring.dao.UserDao;    public class Usermanagerimpl implements usermanager{        private Userdao Userdao;        Use the Set value method to assign the public      void Setuserdao (Userdao userdao) {          This.userdao = Userdao;      }            @Override public      void AddUser (string userName, string password) {            userdao.adduser (userName, password);      }  }  
Constructor Injection

constructor injection, that is, the setting of dependencies is done through the constructor. Let's look at the spring configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmln           S: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-4.1.xsd http://www.springframework.org/schema/a Op http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http: Www.springframework.org/schema/tx/spring-tx-4.1.xsd "> <!--Using spring to manage object creation, and object dependencies--<bean I D= "Userdao4mysql" class= "Com.tgb.spring.dao.UserDao4MysqlImpl"/> <bean id= "userdao4oracle" class= "com.tgb.sp          Ring.dao.UserDao4OracleImpl "/> <bean id=" Usermanager "class=" Com.tgb.spring.manager.UserManagerImpl "> <!--(1) usermAnager uses USERDAO,IOC to automatically create the appropriate Userdao implementations, all of which are managed by the container-<!--(2) to provide constructors in Usermanager, so that spring will inject Userdao implementation (DI) over--&G          T      <!--(3) Let spring manage the creation and dependency of our objects, you must configure the dependencies to spring's core configuration file--<constructor-arg ref= "Userdao4oracle"/>   </bean> </beans>
Let's take a look again, the constructor represents the way the dependency is written, and the code looks like this:

Import Com.tgb.spring.dao.UserDao;    public class Usermanagerimpl implements usermanager{        private Userdao Userdao;        Use construct to assign the value public      Usermanagerimpl (Userdao userdao) {          This.userdao = Userdao;      }        @Override public      void AddUser (string userName, string password) {            userdao.adduser (userName, password);      }  }  
Interface Injection && Setter injection && constructor injection
Interface injection:

Interface injection mode because it is intrusive, it requires that the component must be associated with a specific interface, so it is not optimistic, the actual use is limited.
Setter Injection:
For programmers accustomed to the development of traditional javabean, it is more intuitive to set the dependency relationship by setter method. If the dependencies are more complex, then the constructors for constructing the sub-injection pattern will be quite large, while the value injection pattern is more concise. If a third-party class library is used, our component may be required to provide a default constructor, and the construction sub-injection mode does not apply at this time.
Constructor injection:
complete a complete, legitimate object during construction. All dependencies are rendered centrally in the constructor. Dependencies are set at the time of construction by the container and remain in a relatively "constant" state after the component is created. Only the creator of the component cares about its internal dependencies, and for the caller, the dependency is in the black box.

Small Series of words: The blog, the small part of the main introduction of control inversion, dependency injection and the IOC in spring three injection methods, with the demo to explain, the shortcomings, but also please the small partners to advise, in fact, small series feel, Whether control inversion or dependency injection has the greatest impact on programming, not from the code, but from the ideological change, the "master-slave transposition" has occurred. The application was originally the boss, to get what resources are active attack, but in Ioc/di thought, the application becomes passive, passively wait for the Ioc/di container to create and inject the resources she needs. This action effectively separates the object from the external resources she needs, makes them loosely coupled, facilitates functional reuse, and, more importantly, makes the entire architecture of the program very flexible.

"SSH series" three kinds of dependency injection methods in the spring IOC

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.