SPRINGMVC Learning (what is dependency injection)

Source: Internet
Author: User

In the previous blog post, we learned that Springioc, also known as spring control inversion, will be the object of the creation of destruction and other operations to the spring container to handle, today to learn spring's dependency injection, then what is dependency injection, said the popular point, is the property assignment,  That is, we use spring to assign values to the properties contained in our class, and think of the way we wrote the code before: interface object = new Interface implementation class (); And look at how we've been assigning attributes to properties before.

1. Through the Set method

2. By way of construction

Today we are implementing a spring dependency injection to assign a value to a variable in a class. First I create a new Student.java and a Teacher.java class, and provide a get and set method

Package Com.test.di;public class Student {private string name;private int id;public String getName () {return name;} public void SetName (String name) {this.name = name;} public int getId () {return ID;} public void setId (int id) {this.id = id;}}
Package Com.test.di;public class Teacher {private string teachername;private Student student;public string Getteachername () {return teachername;} public void Setteachername (String teachername) {this.teachername = TeacherName;} Public Student getstudent () {return Student;} public void Setstudent (Student Student) {this.student = Student;}}
We then assign values to these properties in the Spring configuration file:

<?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-2.5.xsd "><bean id=" student "class=" Com.test.di.Student "><property name=" name "value=" haha "></property><property name=" id "value=" 12 "></property></bean><bean id=" Teacher "class=" Com.test.di.Teacher "><property name=" TeacherName "value=" Teacherwang "></property><property name=" student "ref=" student "></property ></bean></beans>
According to the configuration file, we can find that there is a property in the bean configuration, where name is I want to assign a value for that attribute, for the value of the property, there are two cases:

1. If it is a basic type, write the value directly in value to

2. If it is a reference type, it is necessary to use ref to refer to the corresponding class, for this chestnut, that is, student ref here refers to the student that is the first student of the bean in the configured ID.

Next, I write a test class to test whether the property is successfully injected with the corresponding value Ditest.java

ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext ("Com/test/di/applicationcontext.xml"); Teacher Teacher = (Teacher) applicationcontext.getbean ("Teacher"); Student Student = Teacher.getstudent (); System.out.println (Teacher.getteachername ()); System.out.println ("Studentname:" +student.getname () + "==studentid:" +student.getid ());
The results are printed as follows:

Teacherwang
Studentname:haha==studentid:12

This time the spring container has been assigned the value of our property successfully. However, we do not call the Set method as before, or the construction method, here is a point to explain, that is, although we do not call the Set method to assign a value to the property, but spring will still fall in the set method, so if we want to do a dependency injection of a property, Then we need to write the set method on this property.

Here we inject some sets for teacher, the first thing we need to do is to declare list,set,map these three properties in Teacher.java, and then generate a set method for these properties, the new properties are as follows:

Private List<string>lists;private set<integer>sets;private map<integer,string>maps;
It is then assigned a value in the Spring configuration file:

<bean id= "Teacher" class= "Com.test.di.Teacher" ><property name= "TeacherName" value= "Teacherwang" ></ Property><property name= "Student" ref= "student" ></property><property name= "lists" ><list ><value>one</value><value>two</value><value>three</value></list> </property><property name= "Maps" ><map><entry key= "1" value= "Firstmap" ></entry>< Entry key= "2" value= "Secondmap" ></entry><entry key= "3" value= "Thirdmap" ></entry></map> </property><property name= "Sets" ><set><value>111</value><value>222</ Value><value>333</value></set></property></bean>
It can be found that this configuration file is similar to the Normal collection object form, where we are all using the basic type as the generic of the collection, if the use of reference type, where the configuration has a ref corresponding to the property, only need to write the ID of the class object to be referenced in the value of ref. Give me a chestnut:

For list and set if the generic is a reference type, you can write this:

<ref bean= ""/>

And for map, if the type is a reference type, you can write this:

<entry key-ref= "" value-ref= "" ></entry>

Well, it's time to verify that the assignment was successful. Ioctest.java

ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext ("Com/test/di/applicationcontext.xml"); Teacher Teacher = (Teacher) applicationcontext.getbean ("Teacher"); Student Student = Teacher.getstudent (); System.out.println (Teacher.getteachername ()); System.out.println ("Studentname:" +student.getname () + "==studentid:" +student.getid ()); list<string> lists = Teacher.getlists (); for (string string:lists) {System.out.println (string);} Map<integer,string>maps = Teacher.getmaps (); for (Entry<integer,string>entry:maps.entryset ()) { System.out.println (Maps.get (Entry.getkey ()));} Set<integer>sets = Teacher.getsets (); for (integer integer:sets) {System.out.println (integer);}
The results of this printing are as follows:

Teacherwang
Studentname:haha==studentid:12
One
Both
Three
Firstmap
Secondmap
Thirdmap
111
222
333

It can be found that this time spring successfully assigned all the properties that wrote the Set method. All right, the above is all using the Set method to assign a value to the property, let's use the constructor method to assign a value to the property, we write a Classinfo.java class:

Package Com.test.di;public class ClassInfo {private string classname;private Student student;public ClassInfo (String ClassName, Student Student) {super (); this.classname = Classname;this.student = Student;} Public String GetClassName () {return className;} Public Student getstudent () {return Student;}}


We can see that at this point we declare two properties, a basic type, a reference type, and write the constructor method, then we can assign a value to the property in the spring configuration file using the constructor method, in the bean configuration there is such a configuration

<constructor-arg index= "" type= "" ref= "" value= "" ></constructor-arg>

As the name implies, according to the constructor to assign a value to the property, explain the meaning of these four parameters:

Index: The position of the parameter in the constructor method, starting from 0 by default

Type: The types of this parameter

Ref: If the parameter is a reference ID when the type is referenced

Value: If the parameter is a base type

Knowing the meaning of each parameter, it is very simple to write, my classinfo.java corresponding Bean is as follows:

<bean id= "ClassInfo" class= "Com.test.di.ClassInfo" ><constructor-arg index= "0" type= "java.lang.String" Value= "TestConstructor" ></constructor-arg><constructor-arg index= "1" type= "com.test.di.Student" ref= " Student "></constructor-arg></bean>
Write the test code:

ClassInfo ClassInfo = (ClassInfo) applicationcontext.getbean ("ClassInfo"); System.out.println ("Classinfo.getclassname ():" +classinfo.getclassname ()); System.out.println ("StudentID:" +classinfo.getstudent (). GetId () + "==studentname" +classinfo.getstudent (). GetName ( ));
At this point we will correctly agree to the information we set, as follows:

Classinfo.getclassname (): TestConstructor
Studentid:12==studentnamehaha

Now that we've learned how to assign a value to a property in spring, like we did before, we didn't call set or construct a method, but we succeeded in assigning a value to the property, in fact we took the call of the set method to spring to deal with, so what's the use of dependency injection? Why should we learn to rely on injection? Remember the first time I wrote this sentence: interface object = new Interface implementation class (); This is the way we created the object before. Now I'll give you a chestnut:

I created an excuse bookread and then built two classes to implement the interface:

Package Com.test.why.di;public interface Bookread {public void Readbook ();
Package Com.test.why.di;public class Kindleread implements Bookread {@Overridepublic void Readbook () { System.out.println ("Use Kindle read");}}
Package Com.test.why.di;public class Phoneread implements Bookread {@Overridepublic void Readbook () {System.out.println ("Use phone read");}}
Package Com.test.why.di;public class Readby {private Bookread bookread;public Readby (bookread bookread) {this.bookread = Bookread;} public void Read () {Bookread.readbook ();}}

What if I need to read the Kindle first? Follow the previous wording:

Bookread bookread = new Kindleread (); Readby Readby = new Readby (bookread); Readby.read ();
So the question is, if I need to use my phone to read now, do I need to re-phoneread a new one? This is not what we want for interface-oriented programming. Next we use spring's dependency injection to optimize for it:

First, the classes of the two reading methods are configured in the Spring container:

<bean id= "Kindleread" class= "Com.test.why.di.KindleRead" ></bean><bean id= "Phoneread" class= " Com.test.why.di.PhoneRead "></bean>
Then configure the readby corresponding Bean:

<bean id= "Readby" class= "com.test.why.di.ReadBy" ><property name= "Bookread" ref= "Kindleread" ></ Property></bean>
Test:
ApplicationContext ApplicationContext = new Classpathxmlapplicationcontext ("Com/test/di/applicationcontext.xml"); Readby Readby = (readby) applicationcontext.getbean ("Readby"); Readby.read ();

Here I inject for readby is kindleread, so this time I call Readby.read (), the method should be run Kindleread Readbook, actually here has done interface programming, is my readby.read (); Do not need to know what type Bookread is, I only need to call in the Read method call Bookread.readbook (); method, and in which way to read, I just need to configure in the spring container, Doing so also makes the code easier to maintain.

Well, today's springdi to learn here.

Source Download
















SPRINGMVC Learning (what is 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.