I. Dependency Injection (DI)
Dependency injection sounds very advanced, but in fact the vernacular is: assigning values to attributes. There are two methods, the first is in the form of constructor parameters, the other is in the form of setting method.
1 constructor Injection
1 using constructor injection
Using XML as a way to inject
A. Order of parameters
<constructor-arg index= "0" ><value> John </value></constructor-arg>
<constructor-arg index= "1" ><value>56</value></constructor-arg>
B. By type of parameter
<constructor-arg type= "Java.lang.Integer" ><value>56</value></constructor-arg>
<constructor-arg type= "java.lang.String" ><value> John </value></constructor-arg>
Concrete examples
If you want to inject parameters into a person class now, student is a different class.
public class Person {
private String pid;
private String name;
Private Student Student;
Public person (String PID, Student Student) {
this.pid= pid;
This.student = student;
}
Public person (string pid, string name) {
this.pid = pid;
this.name = name;
}
Configuration Applicationcontext.xml, if not the parameter configuration, then the error, the corresponding constructor could not be found. If the corresponding parameter is configured, the corresponding constructor should be declared in the class.
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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=" person "class="
Com.itheima10.spring.di.xml.constructor.Person "> <!--does not match parameters, will take a default constructor Constructor-arg one of the constructor in the person class one of the parameters Index is the type value of the angular type parameter of the parameter if it is the underlying property, the assignment ref reference type is assigned--> <constructor-arg index= "0" type= "ja Va.lang.String "value=" AAA "></constructor-arg> <constructor-arg index=" 1 "ref=" Student "></
constructor-arg> </bean> <bean id= "Person1" class= "Com.itheima10.spring.di.xml.constructor.Person" > <property name= "pid" value= "1" ></property> </bean> <bean id= "Student"
Com.itheima10.spring.di.xml.constructor.Student "></bean> </beans>
Write the test class dixmlconstructortest, do breakpoint debugging, will find that according to configuration parameters, enter the constructor is person (String pid, Student Student)
public class Dixmlconstructortest {
@Test public
void Test1 () {
ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
person who = (person) context.getbean (' person ');
}
2 injecting using the property setter method
Using XML as a way to inject:
A. Injection of simple beans
A simple bean consists of two types: wrapper type and string
<bean id= "Personservice" class= "Com.itcast.bean.impl.PersonServiceImpl" >
<!--basic type, String type-->
<property name= "age" value= "M" ></property>
<property name= "name" value= "Zhang Mowgli" ></ Property>
</bean>
B. Referencing other beans
<bean id= "Person" class= "Com.itcast.bean.Person"/> <bean id= "Personservice"
Com.itcast.bean.impl.PersonServiceImpl ' >
<property name= ' person ' ref= ' person '/>
</bean>
1.1 Assembly List Collection
<property name= "lists" >
<list>
<value>list1</value>
<value>list2</ value>
<ref bean= "person"/>
</list>
</property>
1.2 Assembling Set Sets
<property name= "Sets" >
<set>
<value>list1</value>
<value>list2< /value>
<ref bean= "person"/>
</set>
</property>
1.3 Assembly Map
<property name= "Maps" >
<map>
<entry key= "" >
<value>map01</value>
</entry>
<entry key= ">
<value>map02</value>
</entry>
<" /map>
</property>
The value of <entry> in the map is the same as <list> and <set>, so that any valid attribute element should be noted that the key value must be string.
1.4 Assembly Properties
<property name= "Props" >
<props>
<prop key= "" >prop1</prop>
<prop key= " >prop2</prop>
</props>
</property>
Concrete examples
1. Create two objects person and student
Package Xgp.spring.demo;
Import java.util.List;
Import Java.util.Map;
Import java.util.Properties;
Import Java.util.Set;
public class Person {
private String pid;
private String name;
Private Student Student;
Private List lists;
Private Set sets;
Private Map map;
Private properties Properties;
Private object[] objects;
Public person () {
System.out.println (' new person ');
}
Omit getter and Setter methods
}
Package Xgp.spring.demo;
public class Student {public
Student () {
System.out.println ("New Student");
}
public void Say () {
System.out.println ("student");
}
Configuring Applicationcontext.xml Files
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 > <!--put the person and student into the spring container Property used to describe the attribute value of the person class if it is a generic property, assign ref with value if the property is a reference type, assign the value in ref--> <bean id= "Person" class= Com.itheim A10.spring.di.xml.setter.Person "init-method=" Init "lazy-init=" true "> <property name=" pid "value=" 1 ">< /property> <property name= "name" value= "King II" ></property> <property name= "student" ref= "Student" & gt;</property> <property name= "lists" > <list> <value>list1</value> <value>
;list2</value> <ref bean= "student"/> </list> </property> <property name= "Sets" > <set> <value>set1</value> <value>set2</value> <ref bean= "student"/> </set> </property> <property name= "M AP "> <map> <entry key=" Entry1 "> <value>map1</value> </entry> <entr Y key= "Entry2" > <ref bean= "student"/> </entry> </map> </property> <property Name= "Properties" > <props> <!--do not need reference types--> <prop key= "Prop1" >prop1</prop>
; <prop key= "Prop2" >prop2</prop> </props> </property> <property name= "Objects" > < list> <value>aa</value> <value>bb</value> </list> </property> </be
An> <bean id= "student" class= "com.itheima10.spring.di.xml.setter.Student" ></bean> </beans>
Write test class Dixmlsettertest
Package xgp.spring.test;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Xgp.spring.demo.Person; What the public class Dixmlsettertest {/** * Spring container does: * 1, what does the spring container do? (1) Start the Spring container * (2) To create objects for person and student two beans * (3) Parse the property's name attribute, splice the setter method, parse the properties of the * Valu
e or ref attributes, which pass parameters to the setter method and assign values to the object using reflection techniques.
* (4) Extract the object from the spring container, and the object invokes the method.
* 2, what is the order of the spring container execution? */@Test public void Test1 () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"
);
person who = (person) context.getbean (' person ');
System.out.println (Person.getpid ());
System.out.println (Person.getname ());
System.out.println (Person.getlists ());
System.out.println (Person.getsets ());
System.out.println (Person.getmap ());
System.out.println (Person.getobjects (). length); }/*1 Harry [List1, List2, xgp.spring.demo.student@76a9b9c] [Set1, Set2, xgp.spring.demo.student@76a9b9c] {entry1=map1, entry2=map2} 2*/
Order of execution of the spring container
1. All default settings
2. Set Student (Lazy-init=true)
3. Set person (lazy-init=true)
Summarize
you can inject parameters in two ways, the constructor to write the corresponding constructor, the setter to generate the appropriate setter method, and write the default builder.
The significance of 2.5 IOC and DI
What's the point of learning these things? Here is a document management system example to illustrate the need to see the following figure
1. Writing the Document interface
Public interface Document {public
void read ();
public void Write ();
}
2, the writing implements the class Worddocument, Exceldocument, pdfdocument
public class Worddocument implements document{public
void Read () {
System.out.println ("word read");
}
public void Write () {
System.out.println ("Word write");
}
3, write the document management system Documentmanager
public class Documentmanager {
private document document;
public void Setdocument (document document) {
this.document = document;
}
Public Documentmanager () {
} public
Documentmanager (document document) {
super ();
this.document = document;
}
public void Read () {
this.document.read ();
}
public void Write () {
this.document.write ();
}
}
4, write test class Documenttest
/** * Use IOC and DI to achieve full interface-oriented programming */public class Documenttest {/** * Document document = new Worddocument (); * This line of code is not fully interface-oriented programming because the right side of the equal sign has a specific class/@Test public void testdocument_nospring () {Document document = new Worddocument (
);
Documentmanager Documentmanager = new Documentmanager (document);
Documentmanager.read ();
Documentmanager.write (); /** * Does not know who is implementing the document on the code side, which is determined by the spring configuration file * <bean id= "Documentmanager class=" Com.itheima10.spring.io
Cdi.document.DocumentManager "> <!--document is an interface--> <property name=" Document "> <!-- Worddocument is an implementation class that assigns values to the document interface--> <ref bean= "pdfdocument"/> </property> </bean&
Gt */@Test public void testdocument_spring () {ApplicationContext context = new Classpathxmlapplicationcontext ("app
Licationcontext.xml ");
Documentmanager Documentmanager = (documentmanager) context.getbean ("Documentmanager");
Documentmanager.read (); DocumeNtmanager.write ();
}
}
From the above you can see the difference between spring and the applicable spring
<!--
documentmanager,worddocument,exceldocument,pdfdocument into the spring container
-->
<bean id= " Worddocument "class=" com.itheima10.spring.iocdi.document.WordDocument "></bean>
<bean id=" Exceldocument "class=" com.itheima10.spring.iocdi.document.ExcelDocument "></bean>
<bean id=" Pdfdocument "class=" com.itheima10.spring.iocdi.document.PDFDocument "></bean>
<bean id=" Documentmanager "
class=" Com.itheima10.spring.iocdi.document.DocumentManager ">
<!--
Document is an interface
-->
<property name= "Document" >
<!--
Worddocument is an implementation class, Assign value to document interface
-->
<ref bean= "pdfdocument"/>
</property>
</bean>
Using spring, you only need to configure the corresponding <ref bean= "" > Objects in ApplicationContext without having to focus on the specific implementation classes and implement full interface-oriented programming, which is why spring can integrate with so many tools.
2.6 MVC Example – simulate structs2
Requirements Description
Set up the engineering catalogue
Coding:
1. Create DAO Layer
Establish Persondao interface and implementation class Persondaoimpl
Public interface Persondao {public
void Saveperson ();
}
public class Persondaoimpl implements Persondao {
@Override public
void Saveperson () {
System.out.println ( "Save Person");
}
2, the Establishment service layer, the Personservice interface and the Personserviceimpl implementation class
Public interface Personservice {public
void Saveperson ();
}
public class Personserviceimpl implements personservice{
private Persondao Persondao;
public void Setpersondao (Persondao persondao) {
This.persondao = Persondao;
}
@Override public
void Saveperson () {
this.personDao.savePerson ();
}
}
3. Establish Action,personaction class
public class Personaction {
private personservice personservice;
public void Setpersonservice (Personservice personservice) {
this.personservice = Personservice;
}
public void Saveperson () {
this.personService.savePerson ();
}
}
4. Configure Applicationcontext.xml
<!--
put service,dao,action layers into the spring container
-->
<bean id= "Persondao" class= " Xgp.spring.demo.PersonDaoImpl "></bean>
<bean id=" Personservice "class=" Xgp.spring.demo.PersonServiceImpl ">
<property name=" Persondao ">
<ref bean=" Persondao "/>
</property>
</bean>
<bean id= "personaction" class= "Xgp.spring.demo.PersonAction" >
<property name= "Personservice" >
<ref bean= "Personservice"/>
</property>
</bean>
5, write test class Testmvc
public class Mvctest {
@Test public
void Testmvc () {
ApplicationContext context =
New Classpathxmlapplicationcontext ("Applicationcontext.xml");
Personaction personaction = (personaction) context.getbean ("Personaction");
Personaction.saveperson ();//save person
}
}
The above example clearly shows spring's interface-oriented programming, where the service layer simply invokes the DAO layer's interface without having to focus on the implementation class of the DAO layer, and the action simply invokes the service's interface without needing to focus on the service implementation class.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.