Easy to understand control inversion and dependency injection in spring (i)

Source: Internet
Author: User

Translated from: https://www.cnblogs.com/xxzhuang/p/5948902.html

We look back on the history of the computer, from the first computer to occupy an area of 170 square meters, weighing 30 tons, to today's personal notebooks, things more lightweight function is more rich, this is a trend in the development of things, in the technical field is also the same, Enterprise JavaBean, EJB, was very successful at the time of its creation, but as the years began to chase more convenient and lightweight technical frameworks, spring was JavaBean And spring has been constantly involved in other areas (no more detail here), and the essence of spring includes control inversion and dependency injection.

On control inversion ( Inversion of Control,ioc

Let's first look at the control of the word, that is, in the case of control " positive ", in any of the requested system, at least two classes need to work with each other, under one entry class using the New keyword to create another class object instance, This is like the idea of object-oriented programming,"I" acts as a portal class, in this portal class, I have to buy a pair of disposable chopsticks every time I eat (every use is new), in such a relationship, is "I" (that is, the caller) every time to " active "to buy disposable chopsticks (another class), I said to the chopsticks you honestly come over my hand, I control the chopsticks, that good, in this control is the relationship, put in real life, is certainly unrealistic, and people are lazy, he always to create more convenient for their own life ideas, More precisely, buy a pair of ordinary chopsticks (not disposable), put him in a container (called the IOC Container in spring), you need to use the container said:IOC I want to use chopsticks (request to the container), and then the chopsticks will be "injected" into the hand, In this process, you are no longer the controller , but instead become a requester (although itself or the caller), relying on the container to give you resources, control is located in the container, so this is commonly known as the control reversal .

Initial Dependency Injection ( Dependency Injection

The same goes for the example above, in the unity of control inversion, how chopsticks come to my hand (i.e. how we get the requested class), which is a process of dependency injection.

Another talk on IOC and DI

The principles of the Hollywood principles described in the"Don't call us, we're looking for you", the Baidu encyclopedia on this description is "Do not give us a call, we will give you a call (don ' t calls us, we'll be calling you)" This is the famous Hollywood principle. In Hollywood, when you submit your resume to an acting company, you only have to wait home. The full control of the whole entertainment by the Performing Arts company, the actor can only passively accept the company's errand, in the necessary link, complete his performance. This is a perfect presentation. In the IOC, the IOC is focused on design thinking, from a routine creation of objects, namely the new object, to the IOC container to submit a "resume", passively waiting for the IOC container to return the resources to you. Control reversal refers to the "show company control Actors", and when it comes to dependence, "actors need company bread where", we need to rely on the object of the container to obtain, the process is to rely on injection. in essence, IOC and di are manifestations of different dimensions under the same thought .

Code implementation

Since the process of acquiring resources in control reversals is called Dependency Injection, the code implementation here is also focused on dependency injection. There are 3 ways of dependency injection, namely, construction injection, set injection, and interface injection.

1. interface Injection : Define the information to be injected in the interface and complete the injection through the interface. (Spring does not support this type of injection-the reason why it is not supported is that--spring claims that it is a non-intrusive "live out of this framework," if the use of interface injection, it violates this principle), here does not do the code implementation explanation.

2.Setter Injection

  Let's start with spring to implement setter injection, in two steps, first we look at the relationship between classes under normal practice, the second step is to use IOC to design the class, to compare the differences.

Under the conventional approach

public class userdao{public   void AddUser (String username) {   System.out.println ("Add User:" +username);  }  }
public class Usermessage {   String username= "demo";   Userdao Userdao;   Public usermessage () {   userdao=new Userdao ();  }         public void AddUser () {  userdao.adduser (username);  }  }

  

public class test{  usermessage usermessage=new usermessage ();  Usermessage.adduser ();}

There is a flaw in the code above, because the Usedao object is created inside usermessage, which results in a high degree of coupling between the two classes, and when the project manager wants to implement AddUser with another DAO class, I need to modify the user Message code, re-new another class, if there are 100 places in the system to use this class, then we all have to modify all these places, the probability of the bug will be greatly increased, and then after a while, the project manager said I want to change back to the previous DAO class ...

Let's look at the implementation of the IOC design

public interface userdao{  void AddUser (String username);      
public class Userdaoimpl implements userdao{    @Override public        void AddUser (String username) {    System.out.println ("Add User:" +username);  }  }

public class usermessage{            private Userdao Userdao;            Use the Set value method to assign the public        void Setuserdao (userdao userdao) {            This.userdao = Userdao;        }        public void AddUser (string userName, string password) {                  userdao.adduser (userName);        }    }   

  

public class test{public    static void Main (string[] args) {        Userdao Userdao =new Userdaoimpl ();        Usermessage usermessage=new usermessage ();        Usermessage.setuserdao (Userdao);    }}

We look closely at the practice here, Userdao userdao=new Userdaoimpl () approach, we have to mention the polymorphism, that is, the parent class can refer to the method of the subclass, where the effect is to reduce the user message and Userdao coupling degree. Because there is only connection between Usermessage and Userdao (AddUser method), User message does not understand how Userdaoimpl is implemented. When we need to switch to another Userdao implementation class, we just need to change the code on the first line under the test class, and there's no need to change the usermessage inside.

Think again, the reader may say wrong ah, you say control inversion and dependency injection need to request resources to the container, this container does not come out on the above, we will explain how spring is injected.

  

  <!--using spring to manage object creation, as well as object dependencies--    <bean id= "Usermanager" class= "Scau.zzf.service.UserMessage" >            <!--(1) Usermessageimpl uses USERDAO,IOC to automatically create corresponding Userdao implementations, all managed by the container-            <!--(2) Provide a constructor in Usermessageimpl to let spring bring the Userdao implementation (DI) back--            <!--(3) Let spring manage the creation and dependency of our objects, Dependencies must be configured in spring's core configuration file-            <property name= "Userdao" ref= "Userdao" ></property>       <!-- Construction injection-    <!--<constructor-arg ref= "Userdao"/>--     </bean>   <bean id= " Userdao "class=" Scau.zzf.Dao.UserDao ">    </bean>    

First we need to assemble the bean, that is, after the bean is configured in the Spring container, and then return the Bean object instance. We can read our XML file through Xmlbeanfactory to get the relevant bean information.

public class Test {public    static void Main (string[] args) throws Exception {    beanfactory factory=new xmlbeanfacto Ry (New Filesystemresource ("Src/appllication.xml"));        Usermessage usermessage= (usermessage) Factory.getbean ("Usermessage");        Usermessage.add ("Demacia");}    }

In practical applications, we do not manually read the information in the XML or load the configuration file, the spring bottom has helped me do this, that is, in the actual application, we just need to send a request, of course, it is necessary to understand such a process.

Here's a quick walkthrough of how to inject with annotations.

@Configurationpublic class Userconfig {    @Bean public    Userdao Getuserdao () {        return new Userdao ();    @Bean public    usermessage getusermessage () {        return new usermesssgae (Getuserdao);    }
@Configuration's role is to make the entire class A configuration class, @Bean annotations will tell spring that the method under this annotation will return an object that will register the bean for the dimension Spring application context. By default, spring's beans are singleton, that is, in the example above, no matter how many times we use Getuserdao (), the returned object will be the same from the beginning to the end.


Translated from: https://www.cnblogs.com/xxzhuang/p/5948902.html

Easy to understand control inversion and dependency injection in spring (i)

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.