DI: assign values to attributes
spring calls the parameterless construction method of the class to create an object. Assign a value to the property after the object is created.
To assign a value to an attribute, you can use:
- Tags and attributes in xml configuration files
- Using annotations
DI classification:
- Set injection is also called set injection
- Structural injection
set injection
public class Student { //full name private String name; //Age private int age; //Parameterless constructor public Student() { System.out.println("Student Nonparametric construction method"); } public void setName(String name) { System.out.println("setName==="+name); this.name = "Hello:"+name; } public void setAge(int age) { System.out.println("setAge=="+age); this.age = age; } public void setEmail(String email){ //Email attribute < property name = "email" value=“ lisi@qq.com " /> System.out.println("setEmail==="+email); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Define a Student class:
Define attributes: name and age
The set method that generates them
Note: the attribute email is not defined above, only the set method (setEmail) is generated
Override toString method
Define applicationContext configuration file:
set injection
property Used to bind properties: name Is the name of the property to bind set There are two types of injection: normal type and reference type. Common type: java Basic data types and in String. Reference type: all reference types except the basic data type(Except here`String`) Common type assignment use value="" Reference type assignment use ref=""
Common type set injection
Profile:
<?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"> <!--statement bean--> <!--Common type set injection--> <bean id="myStudent" class="com.bjpowernode.ba01.Student"> <property name="name" value="Li Si"/><!--setName("Li Si")--> <property name="age" value="22" /><!--setAge(22)--> <property name="email" value="lisi@qq.com" /><!--setEmail("xxx)--> </bean> <!--Declaration date class--> <!--It's bound here time Property, the setTime()method Java Date Class setTime()Method to set a date object. It sets the date object to represent January 1, 1970 00 GMT:00:00 Time after Ms. usage: public void setTime(long time) Parameter: the function accepts a single parameter time, which specifies the number of milliseconds. --> <bean id="mydate" class="java.util.Date"> <property name="time" value="933295249276"/><!--setTime()--> </bean> </beans>
Common type set injection syntax:
set Injection: spring Calling class set Method, by set Method to complete the attribute assignment Simple type set Injection: Syntax: <bean id="xxx" class="yyy"> <property name="Attribute name" value="Simple type property value"/> ... </bean>
Define test class:
public class MyTest01 { @Test public void test01(){ //Specify the name and path of the configuration file String config="applicationContext.xml"; //Get spring container object ApplicationContext ctx = new ClassPathXmlApplicationContext(config); //Get student custom object from container Student student = (Student) ctx.getBean("myStudent"); //Call student's toString method System.out.println("student="+student); //Get the Date object Date provided by java from the container Date date = (Date) ctx.getBean("mydate"); //Print date System.out.println("date==="+date); } }
Analysis print order:
- First, spring creates objects by calling the class's parameterless constructor, so the first print is the Student class's constructor that cannot be constructed
- Then, when spring performs set injection, it will call the set method corresponding to the attribute. When calling, it will change the initial letter of your attribute name to uppercase (if the initial letter of the attribute is uppercase, that is, the letter remains unchanged), and then add set in front of it, so as to call the set method corresponding to the attribute. Since setName() and setAge() are both performing attribute assignment and printing operations, setEmail() method only performs printing operations. Since no attribute email is defined, sequence 2 performs printing operations in setName(), setEmail(), and setEmail()
- The student object is printed in the test class. Since the toString method is overridden, the toString method in the student will be called to print information
- Finally, the Date object is printed in the test class. Since the toString method of the Date object is also rewritten and returns time information, the last step is to print time information
Run test:
Reference type set injection
Define a School class:
Defining attributes: common types name and address
The set method that generates them
Override toString method
public class School { private String name; private String address; public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "School{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
Define a Student class:
Define attributes: common type name and age, reference type school
The set method that generates them
Note: the attribute email is not defined above, only the set method (setEmail) is generated
Override toString method
public class Student { private String name; private int age; //reference type private School school; public Student() { System.out.println("Student Nonparametric construction method"); } public void setName(String name) { System.out.println("setName==="+name); this.name = "Hello:"+name; } public void setAge(int age) { System.out.println("setAge=="+age); this.age = age; } public void setSchool(School school) { System.out.println("setSchool="+school); this.school = school; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", school=" + school + '}'; } }
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.xsd"> <!--statement School--> <bean id="mySchool" class="com.bjpowernode.ba02.School"> <property name="name" value="Peking University"/> <property name="address" value="Haidian District "/> </bean> <!--reference type set injection--> <bean id="myStudent" class="com.bjpowernode.ba02.Student"> <property name="name" value="Li Si"/> <property name="age" value="22" /> <!--Assignment of reference type--> <property name="school" ref="mySchool" /><!--setSchool(mySchool)--> </bean> </beans>
Reference data type set injection syntax:
set Injection: reference type set Injection: Syntax:<bean id="xxx" class="yyy"> <property name="Attribute name" ref="bean of id"/> ... </bean>
Define test class:
public class MyTest2(){ @Test public void test01(){ Student student = new Student(); student.setName("lisi"); student.setAge(20); School school = new School(); school.setName("Peking University"); school.setAddress("Haidian District, Beijing"); student.setSchool(school); } }
Test class:
- spring creates objects through the parameterless constructor method, so it will go through all the parameterless constructors
- Because there are printing operations in setName and setAge in student, the name and age will be printed
- Finally, it prints the school object, then calls the toString method, and the school object rewrites the toString method, so it prints the properties of school name and address.
Operation results:
Structural injection
Construction injection: Spring calls the parameterized construction method of the class, creates an object and assigns a value to the attribute
Syntax: <bean id="xxx" class="yyy"> <constructor-arg>: Formal parameters representing a constructor The tag has attributes: name : Constructor parameter name index: Parameter position of construction method value: Parameter value of simple type ref: Parameter value of reference type </bean>
Profile:
<?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"> <!--statement bean--> <!-- Structural injection: Spring Call the parameterized construction method of the class, create the object and assign a value to the attribute at the same time Syntax: <bean id="xxx" class="yyy"> <constructor-arg>: Formal parameters representing a constructor The tag has attributes: name : Constructor parameter name index: Parameter position of construction method value: Parameter value of simple type ref: Parameter value of reference type </bean> --> <!--Construct injection, using name attribute--> <bean id="myStudent" class="com.bjpowernode.ba03.Student"> <constructor-arg name="myage" value="22" /> <constructor-arg name="myname" value="Li Si"/> <constructor-arg name="mySchool" ref="mySchool"/> </bean> <!--Construct injection, using index,The position of the parameter. The position of the construction method parameter from left to right is 0,1,2--> <bean id="myStudent2" class="com.bjpowernode.ba03.Student"> <constructor-arg index="1" value="28"/> <constructor-arg index="0" value="Zhang San"/> <constructor-arg index="2" ref="mySchool" /> </bean> <!--Construction injection, omitted index attribute--> <bean id="myStudent3" class="com.bjpowernode.ba03.Student"> <constructor-arg value="Zhang Feng"/> <constructor-arg value="28"/> <constructor-arg ref="mySchool" /> </bean> <!--statement School--> <bean id="mySchool" class="com.bjpowernode.ba03.School"> <property name="name" value="Peking University"/> <property name="address" value="Haidian District "/> </bean> <!--statement File object--> <bean id="myFile" class="java.io.File"> <constructor-arg name="parent" value="D:\\course"/> <constructor-arg name="child" value="2009 Class network disk.txt" /> </bean> </beans>
Reference type auto injection
Automatic injection of reference types: spring assigns values to reference types according to byname and bytype rules
byName injection:
1.byName(By name): java Property name and name of the reference type in the class spring In container bean of id If the name is the same and the data type is the same, this is the case bean Can be assigned to a reference type. Syntax: <bean id="xxx" class="yy" autowire="byName"> Simple type attribute assignment </bean>
Profile:
<?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"> <!--statement bean--> <!-- byName Automatic injection --> <bean id="myStudent" class="com.bjpowernode.ba04.Student" autowire="byName"> <property name="name" value="Li Si"/> <property name="age" value="22" /> <!--Assignment of reference type--> <!--<property name="school" ref="mySchool" />--> </bean> <!--statement School--> <bean id="school" class="com.bjpowernode.ba04.School"> <property name="name" value="Tsinghua University"/> <property name="address" value="Haidian District "/> </bean> </beans>
byType injection:
2.byType(Injection by type: java The data type and of the reference type in the class bean of class Is homologous, These bean Can be assigned to a reference type. Homology: 1. java Data types and of reference types in bean of class The value is the same. 2. java Data types and of reference types in bean of class Values are parent-child relationships. 3. java Data types and of reference types in bean of class Values are the of the interface and implementation class relationships. Syntax: <bean id="xxx" class="yy" autowire="byType"> Simple type attribute assignment </bean> Note: in xml There can only be one qualified object in the configuration file. The extra one is wrong.
Profile:
<?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"> <!--statement bean--> <!-- byType Automatic injection --> <bean id="myStudent" class="com.bjpowernode.ba05.Student" autowire="byType"> <property name="name" value="Zhang San"/> <property name="age" value="26" /> <!--Assignment of reference type--> <!--<property name="school" ref="mySchool" />--> </bean> <!--statement School--> <bean id="mySchool" class="com.bjpowernode.ba05.School"> <property name="name" value="Aviation University"/> <property name="address" value="Haidian District "/> </bean> <!--statement School Subclass of--> <!--<bean id="primarySchool" class="com.bjpowernode.ba05.PrimarySchool"> <property name="name" value="Beijing Daxing primary school" /> <property name="address" value="Daxing District of Beijing"/> </bean>--> </beans>
Specify multiple Spring configuration files for the application
In practical applications, with the increase of application scale, beans in the system
The number has also increased greatly, resulting in a very large and bloated configuration file. In order to avoid this situation and improve the readability and maintainability of the configuration file, Spring
The configuration file is decomposed into multiple configuration files.
Profiles containing relationships:
There is a master file in multiple configuration files, and the master configuration file passes through other sub files
import tag. In Java code, you only need to initialize the container with the general configuration file.
give an example:
Syntax:
At present, it is a general file. The purpose is to contain multiple other configuration files. It is generally not declared bean Syntax: <import resource="classpath:Path to other files" /> classpath:Represents a classpath. The directory where the class file is located, spring Load configuration file through classpath
Import multiple configuration files through the import tag:
<import resource="classpath:ba06/spring-school.xml" /> <import resource="classpath:ba06/spring-student.xml" />
Wildcards * can also be used. However, at this time, it is required that the parent configuration file name cannot meet the format that * * can match, otherwise circular recursive inclusion will occur. For this example, the parent configuration file cannot match the format of spring-*.xml, that is, it cannot be named spring-total.xml.
Syntax:
Configuration files containing relationships, wildcards can be used(*: (represents any character) Note: the total file name cannot be included in the wildcard range( applicationContext.xml Can't be called spring-applicationContext.xml)
Use wildcard * to introduce multiple profiles:
<import resource="classpath:ba06/spring-*.xml" />