1. Dependency Injection (DI)
Dependency injection sounds very profound, but in fact it is: assign values to attributes. There are two methods in total. The first is in the form of constructor parameters, and the other is in the form of setting method.
1 Constructor injection
1 Inject using the constructor
Injection method using xml
A. Order of parameters
<constructor-arg index="0"><value>Zhang San</value></constructor-arg>
<constructor-arg index="1"><value>56</value></constructor-arg>
B. Type of parameter
<constructor-arg type="java.lang.Integer"><value>56</value></constructor-arg>
<constructor-arg type="java.lang.String"><value>Zhang San</value></constructor-arg>
Specific examples
If you want to inject parameters into a Person class now, Student is another 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; }}Configure applicationContext.xml. If no parameter configuration is performed, an error will be reported and the corresponding constructor cannot be found. If the corresponding parameters are configured, the corresponding constructor should be declared in the class.
<?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="person"> <!-- If the parameters are not matched, the default constructor-arg will be adopted A parameter index of a constructor in person class is the angle mark of the parameter. The type value of the parameter. If it is a basic property, use this assignment ref to refer to the type assign --> <constructor-arg index="0" type="java.lang.String" value="aaa"></constructor-arg> <constructor-arg index="1" ref="student"></constructor-arg> </bean> <bean id="person1"> <property name="pid" value="1"></property> </bean> <bean id="student"></bean></beans>
Write the test class DIXMLConstructorTest and perform breakpoint debugging. You will find that according to the configuration parameters, the constructor entered is Person(String pid, Student student)
public class DIXMLConstructorTest { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person) context.getBean("person"); } }2 Injection using the property setter method
Injection method using xml:
A. Injection of simple beans Simple beans include two types: packaging type and String
<bean id="personService"><!-- Basic type, string type--><property name="age" value="20"></property><property name="name" value="Zhang Wuji"></property> </bean>
B. Quote other beans
<bean id="person" /> <bean id="personService"> <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 Assembly set collection
<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="01"> <value>map01</value> </entry> <entry key="02"> <value>map02</value> </entry> </map></property>
The value of <entry> in the map is the same as that of <list> and <set>, which can make any valid attribute element. It should be noted that the key value must be String.
1.4 Assembly Properties
<property name="props"> <props> <prop key="01">prop1</prop> <prop key="02">prop2</prop> </props></property>
Specific 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 says(){ System.out.println("student"); }}Configure the applicationContext.xml 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"> <!-- Put person and student in spring container property used to describe the property value of the Person class If it is a general property, use value to assign ref. If the property is a reference type, use ref to assign value--> <bean id="person" init-method="init" lazy-init="true"> <property name="pid" value="1"></property> <property name="name" value="Wang Ermazi"></property> <property name="student" ref="student"></property> <property name="lists"> <list> <value>list1</value> <value>list2</value> <ref bean="student"/> </property> <property name="sets"> <set> <value>set1</value> <value>set2</value> <ref bean="student"/> </set> </property> <property name="map"> <map> <entry key="entry1"> <value>map1</value> </entry> <entry key="entry2"> <ref bean="student"/> </entry> </map> </property> <property name="properties"> <props> <!-- No reference type required--> <prop key="prop1">prop1</prop> <prop key="prop2">prop2</prop> </props> </property> <property name="objects"> <list> <value>aa</value> <value>bb</value> </list> </property> </bean> <bean id="student"></bean></beans>
Write a 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;public class DIXMLSetterTest { /** * What does spring container do: * 1. What does spring container do? (1) Start the spring container* (2) Create an object for the two beans of person and student* (3) Analyze the name attribute of the property, splice the setter method, parse the * value or ref attributes of the property, pass parameters to the setter method, and use reflection technology to assign values to the object. * (4) Extract the object from the spring container and call the method of the object. * 2. What is the execution order of spring containers? */ @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (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 Wang Wu[list1, list2, xgp.spring.demo.Student@76a9b9c][set1, set2, xgp.spring.demo.Student@76a9b9c]{entry1=map1, entry2=map2}2*/ The execution order of spring containers
1. All are default settings
2. Set student(lazy-init=true)
3. Set person(lazy-init=true)
Summarize
There are two methods to inject parameters. The constructor needs to write the corresponding constructor, the setter needs to generate the corresponding setter method, and the default constructor is written.
2.5 The significance of IOC and DI
After learning these, what is the meaning of discovering it? Let’s write an example of a document management system to illustrate the requirements. See the figure below
1. Write Document interface
public interface Document { public void read(); public void write();}2. Write implementation classes 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 a DocumentManager system
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 a test class DocumentTest
/** * Using ioc and di, you can achieve complete interface-oriented programming* */public class DocumentTest { /** * Document document = new WordDocument(); * This line of code is not completely interface-oriented programming, because a specific class appears on the right side of the equal sign*/ @Test public void testDocument_NOSPRING(){ Document document = new WordDocument(); DocumentManager documentManager = new DocumentManager(document); documentManager.read(); documentManager.write(); } /** * On the code side, I don’t know who implements the Document. This is determined by the spring configuration file* <bean id="documentManager" > <!-- document is an interface--> <property name="document"> <!-- wordDocument is an implementation class, assigned to the document interface--> <ref bean="pdfDocument"/> </property> </bean> */ @Test public void testDocument_Spring(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DocumentManager documentManager =(DocumentManager)context.getBean("documentManager"); documentManager.read(); documentManager.write(); }}From the above, we can see the difference between not applying spring and applying spring
<!-- documentManager,wordDocument,excelDocument,pdfDocument is put into spring container --> <bean id="wordDocument"></bean> <bean id="excelDocument"></bean> <bean id="pdfDocument"></bean> <bean id="pdfDocument"></bean> <bean id="documentManager" > <!-- document is an interface --> <property name="document"> <!-- wordDocument is an implementation class, assigned to the document interface --> <ref bean="pdfDocument"/> </property> </bean>
Using spring only requires configuring the corresponding <ref bean=""> object in the applicationContext, without paying attention to specific implementation classes and implementing complete interface-oriented programming. This is why spring can integrate with so many tools.
2.6 mvc instance simulation structs2
Requirement description
Create a project directory
coding:
1. Create a Dao layer to establish a PersonDao interface and implement a PersonDaoImpl class
public interface PersonDao { public void savePerson();}public class PersonDaoImpl implements PersonDao { @Override public void savePerson() { System.out.println(" save person"); }}2. Establish a service layer, PersonService interface and 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. Create 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 the service,dao,action class into the spring container--> <bean id="personDao"></bean> <bean id="personService"> <property name="personDao"> <ref bean="personDao"/> </property> </bean> <bean id="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 the interface-oriented programming of spring. The service layer only needs to call the interface of the dao layer, but does not need to pay attention to the implementation class of the dao layer, and the action only needs to call the interface of the service, but does not need to pay attention to the implementation class of the service.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.