Spring Learning (ii)---dependency injection

Source: Internet
Author: User

Spring's second feature is dependency injection.

Learning Dependency Injection, you should first understand two questions: 1, who depends on who, 2, who injected, injected what?

First, look at the code:

Or is this bean:

 PackageTestSpring.business.bean;Importorg.springframework.stereotype.Repository;ImportTestSpring.business.iface.IPrint;/*** UserBean: *@authorXuejupo [email protected] * Create in 2016-2-16 morning 9:22:39*/ Public classUserBeanImplementsiprint{@Override PublicString PrintObject () {//TODO auto-generated Method StubSystem.out.println ("Print object Userbean:"); return"ABC"; }}

Then, my business logic needs to use that bean in this bean:

 PackageTestSpring.business.impl;ImportTestSpring.business.iface.IPrint;/*** Print: *@authorXuejupo [email protected] * Create in 2016-2-16 morning 10:23:37*/ Public classPrint {//The bean that needs to be printed, the injected entry (the object that needs to be injected)    PrivateIPrint Printbean; PrivateString name;  Public voidprint () {System.out.println ("Injected name:" +name);  This. Printbean.printobject (); }        /*** Setprintbean:set method, set injection required method *@paramPrintbean * void return type*/     Public voidSetprintbean (IPrint printbean) { This. Printbean =Printbean; }        /*** Setname:set method, set injection required method *@paramname * void return type*/     Public voidsetName (String name) { This. Name =name; }}

Normal client code that uses the print class:

New Print ();p. Setprintbean (new  UserBean ());p rint.print ();

is also very simple code, but, the client code and the specific class print and Userbean code strongly coupled in a piece, does not conform to the open and closed principle, so you need to use dependency injection into the client code to inject Pring object, into the print class to inject Userbean object.

The XML file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:context= "Http://www.springframework.org/schema/context"xmlns:p= "http://www.springframework.org/schema/p"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-3.2.xsd "><context:annotation-config/> <!--registration JavaBean--<bean id= "UserBean"class= "TestSpring.business.bean.MyBean"/> <!--registered JavaBean--<bean id= "Printbean"class= "TestSpring.business.impl.Print" > <!--injection javabean Parameters--<property name = "Printbean" ref = "User Bean "></property> <property name =" name "value =" haha "></property> </bean></bean S>

Client code:

// Read the configuration file (load the bean in the configuration file into memory)        New Classpathxmlapplicationcontext ("/testspring/resources/applicationcontext.xml");         // gets the instance        Print bean= (print) Ctx.getbean ("Printbean");           // calling methods          Bean.print ();

Printing results:

Injected Name:haha Print Object Mybean:

As you can see, with the configuration information of XML, in the client code without the specific new Java object, the creation of Java objects, and the assignment of elements in the object can be given to the XML (Spring) processing.

Answer the first two questions in the text: 1. In client code, the creation of a specific object is dependent on the XML file (spring, the IOC container), and 2. Is the IOC container injection, in the runtime, based on the XML configuration information, the specific object is injected into the corresponding bean.

Say what you understand in the IOC container: Online Search, nothing let me satisfied with the answer, can only understand. I understand that the IOC container, in fact, is a Web service startup, Tomcat (or other Web server) loads Applicationcontext.xml (the spring configuration file of the registered bean), which creates a chunk of memory in memory that is specifically stored in the XML file and stored in the form of a map map, and key is Id,valu E is the specific bean. This memory area, which is used to store the bean's container, is called the IOC container (which should be called the bean container of Spring in fact) (personally, it is not possible to find a better explanation for this definition, only to understand it first).

If you read my previous blog, I would say that dependency injection and control inversion are different .... They are really the same thing ...   Dependency injection can also be called control inversion, which is to give control to the configuration file. But I personally like this understanding: the registry of the bean is called control inversion, the initialization of parameters in the bean is called Dependency injection. Personally feel, know is a thing on the line, how easy to let you understand how to come.

Talk about the benefits of dependency injection:

The main thing is decoupling. Facilitates switching of data sources: for example, I want to print another bean in the print class, just need to modify the XML file.

This is still a bit false, perhaps the real environment more can explain the problem: the company recently encountered a demand, two people need to jointly develop: a wave of development company intranet interface---a group, a wave of development companies to implement the external (equivalent to the client)---Group B. Client development is dependent on the intranet function, but can not wait for the students to develop the intranet, so the leadership decided: a group of people, the need to implement the function, to interface (interface) the way to burst into Group B students, and then two groups of fragmented, after the development of the merger will be done.

Suppose the group a bursts out an interface as follows:

 Public Interface myinterface{        void  MyMethod ();}

But a group of this interface implementation has not been written, so my group B people want to use this interface programming, two methods (I am a rookie, there may be other ways, can be pointed):

First:

MyInterface bean = null; This requires a post-populate concrete interface implementation

Then, when the Group A's implementation is given to us, we then use the global search to assign the beans all to the specific implementation. At this time, in case a group of people brain a smoke, said Oops, I give you the implementation of the wrong, should be given to group C, you use another, then I have to modify all the code globally .... (This is the strong coupling, the group A changes the code, will cause the B group of people Code must be modified)

Then, the second type is sauce:

With a configuration file:

class= "Xxx.xxx.xxx.xxxx"/><!--Register my JavaBean--    class= " TestSpring.business.impl.Print ">    <!--injection interface implementation--        <property name =" MyInterface "ref =" MyInterface "></property>    </bean>

And then in the JavaBean I've registered, I just need this:

Private MyInterface MyInterface;

You can use the implementation of the interface, and no matter how you change a group, I do not change the code of Group B, only the configuration file (of course, if the interface of a group can not be changed), this is weak coupling, but also the design principle of the well-known dependency inversion principle (depends on the interface and not rely on the implementation).

Spring Learning (ii)---dependency injection

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.