Spring drip seven: Spring in Dependency injection (Dependency Injection:di)

Source: Internet
Author: User

There are two main types of dependency injection in the spring mechanism: constructor-based Dependency injection (based on construction method dependency Injection) and setter-based Dependency injection ( Based on setter method dependency Injection)

first, contructor-based Dependency Injection (based on the construction method Injection)

In the bean tab, use the <constructor-arg/> tag to implement the

Spring.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/schema/beans"Xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "><bean id= "a"class= "com.test.spring.a" >
<!--reference Other beans two different implementations --<constructor-arg><ref bean= "b"/></constructor-arg> <constructor-argref= "c"/> <constructor-arg name= "name" value= "zhang san"/> </bean> <bean id= "b"class= "com.test.spring.b" > </bean> <bean id= "c"class= "com.test.spring.c" > </bean></beans>

Java class:

 packagecom.test.spring; public classA {Privateb b; PrivateC c; PrivateString name;  publicA (b b, c c, String Name) { this. B =b;  this. C =c;  this. Name =name; }     publicB getb () {returnb; }     public voidSetb (b B) { this. B =b; }     publicC GetC () {returnc; }     public voidsetc (c C) { this. C =c; }     publicString getName () {returnname; }     public voidsetName (String Name) { this. Name =name; } @Override publicString toString () {return"A [b=" + B + ", c=" + C + ", name=" + name + "]"; }    }--------------------------------------------------------------------------------------------------------------- ---------------------------------- packagecom.test.spring; public classB {}--------------------------------------------------------------------------------------------------------------- ---------------------------------- packagecom.test.spring; public classC {}

Test:

 packagecom.test.spring;Importorg.junit.Before;Importorg.junit.Test;Importorg.springframework.context.support.AbstractApplicationContext;Importorg.springframework.context.support.ClassPathXmlApplicationContext; public classT {abstractapplicationcontext ApplicationContext=NULL; @Before public voidbefore () {System.out.println ("" Spring ApplicationContext container began to initialize ... "); ApplicationContext=NewClasspathxmlapplicationcontext (Newstring[]{"test1-service.xml"}); System.out.println ("" Spring ApplicationContext Container initialization is complete ... "); } @Test public voidTest () {a a=applicationcontext.getbean (A.class);    System.out.println (a); }}

Test Results:

"Spring ApplicationContext container begins to initialize ...
2017-03-19 14:02:53 info:classpathxmlapplicationcontext-refreshing org[email protected]18c92ff9:startup date [Sun Mar 14:02:53 CST 2017]; Root of context Hierarchy
2017-03-19 14:02:53 info:xmlbeandefinitionreader-loading XML Bean Definitions from class path resource [TEST1-SERVICE.XM L
"Spring ApplicationContext container initialization is complete ...
A [[email protected], [email protected], name= Zhang San]

The Spring website API provides enough to use the static factory approach to achieve these features:

Spring.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/schema/beans"Xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "><bean id= "a"class= "com.test.spring.a"factory-method= "getinstence"> <constructor-arg> <ref bean= "b"/> </constructor-arg> <constructor-arg ref= "c"/> <constructor-arg name= "name" value= "zhang san"/> </bean> <bean id= "b"class= "com.test.spring.b" > </bean> <bean id= "c"class= "com.test.spring.c" > </bean></beans>

Java class:

 packagecom.test.spring; public classA {Privateb b; PrivateC c; PrivateString name; /*** Create a private construction method *@paramb *@paramc *@paramname*/    private A (b b, c c, String name) {this.b = b;        THIS.C = c;    THIS.name = name; }       public static a getinstence (B b,c c,string name) {System.out.println ("called static Factory method");        A = new A (b,c,name);    Return a; }     publicB getb () {returnb; }     public voidSetb (b B) { this. B =b; }     publicC GetC () {returnc; }     public voidsetc (c C) { this. C =c; }     publicString getName () {returnname; }     public voidsetName (String Name) { this. Name =name; } @Override publicString toString () {return"A [b=" + B + ", c=" + C + ", name=" + name + "]"; }    }--------------------------------------------------------------------------------
B.java C.java (slightly)

Test:

 packagecom.test.spring;Importorg.junit.Before;Importorg.junit.Test;Importorg.springframework.context.support.AbstractApplicationContext;Importorg.springframework.context.support.ClassPathXmlApplicationContext; public classT {abstractapplicationcontext ApplicationContext=NULL; @Before public voidbefore () {System.out.println ("" Spring ApplicationContext container began to initialize ... "); ApplicationContext=NewClasspathxmlapplicationcontext (Newstring[]{"test1-service.xml"}); System.out.println ("" Spring ApplicationContext Container initialization is complete ... "); } @Test public voidTest () {A A=applicationcontext.getbean (a.class); A A2=applicationcontext.getbean (A.class); System.out.println (a==A2)        ;//find The instance object of a as a singleton        System.out.println (a);    System.out.println (a2); }}

Test Results:

"Spring ApplicationContext container begins to initialize ...
2017-03-19 14:22:31 info:classpathxmlapplicationcontext-refreshing org[email protected]17ad352e:startup date [Sun Mar 14:22:31 CST 2017]; Root of context Hierarchy
2017-03-19 14:22:31 info:xmlbeandefinitionreader-loading XML Bean Definitions from class path resource [TEST1-SERVICE.XM L
A static factory method is called
"Spring ApplicationContext container initialization is complete ...
True
A [[email protected], [email protected], name= Zhang San]
A [[email protected], [email protected], name= Zhang San]

2.setter-based Dependency Injection (Setter-based Dependency injection): This injection method is often used

Spring.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/schema/beans"     xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"    xsi:schemalocation= "http// Www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/ Spring-beans.xsd ">   class=" com.test.spring.a ">       <property name=" b "ref=" B "/>       <property name= "c" ref= "c"/>       <property name= "name" value= "zhang san"/>    </bean>    class= "com.test.spring.b" >    </bean>    class= "com.test.spring.c" >    </bean></beans>

Java class:

 packagecom.test.spring; public classA {Privateb b; PrivateC c; PrivateString name;  publicB getb () {returnb; }     public voidSetb (b B) { this. B =b; }     publicC GetC () {returnc; }     public voidsetc (c C) { this. C =c; }     publicString getName () {returnname; }     public voidsetName (String Name) { this. Name =name; } @Override publicString toString () {return"A [b=" + B + ", c=" + C + ", name=" + name + "]"; }    }

Test:

 packagecom.test.spring;Importorg.junit.Before;Importorg.junit.Test;Importorg.springframework.context.support.AbstractApplicationContext;Importorg.springframework.context.support.ClassPathXmlApplicationContext; public classT {abstractapplicationcontext ApplicationContext=NULL; @Before public voidbefore () {System.out.println ("" Spring ApplicationContext container began to initialize ... "); ApplicationContext=NewClasspathxmlapplicationcontext (Newstring[]{"test1-service.xml"}); System.out.println ("" Spring ApplicationContext Container initialization is complete ... "); } @Test public voidTest () {//beanlifecycle beanlifecycle =applicationcontext.getbean ("beanlifecycle", beanlifecycle.class); //Applicationcontext.close (); //Applicationcontext.registershutdownhook (); A A=applicationcontext.getbean (a.class);    System.out.println (a); }}

Test Results:

"Spring ApplicationContext container begins to initialize ...
2017-03-19 14:34:20 info:classpathxmlapplicationcontext-refreshing org[email protected]17ad352e:startup date [Sun Mar 14:34:20 CST 2017]; Root of context Hierarchy
2017-03-19 14:34:20 info:xmlbeandefinitionreader-loading XML Bean Definitions from class path resource [TEST1-SERVICE.XM L
"Spring ApplicationContext container initialization is complete ...
A [[email protected], [email protected], name= Zhang San]

Both of these injections can be used together in a spring configuration file

Spring bit seven: Dependency Injection in spring (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.