Spring framework learning notes
Official download address
Video viewing address
https://www.bilibili.com/vide...
1, IOC control reversal
1.1 general
IoC (Inversion of Control) is a concept and an idea. It refers to handing over the call right of the object directly controlled by the program code to the container, and realizing the assembly and management of the object through the container. Inversion of Control is the transfer of control over the object, from the program code itself to the external container. The creation of objects, attribute assignment and dependency management are realized through containers
IoC is a concept and an idea, which is implemented in a variety of ways. Currently, it is dependency injection. Widely used
Dependency: the classA class contains instances of classB, and the method of calling classB in classA completes the function, that is, classA.
It depends on classB.
1.2 implementation of IOC
Dependency injection: DI(Dependency Injection). The program code does not do location query. These tasks are completed by the container itself.
Dependency injection DI means that if another object needs to be called for assistance during program operation, it does not need to be created in the code
Instead, the callee relies on the external container, which is created and passed to the program.
Spring's dependency injection has almost no requirements for callers and callees, and fully supports the dependency relationship between objects
Management of.
The Spring container is a large factory responsible for creating and managing all Java objects, which are called beans.
Spring container manages the dependencies between beans in the container. Spring uses "dependency injection" to manage the dependencies between beans. Use IoC to realize decoupling and between objects.
1.3 about bean Tags
bean tag configuration
<!--tell spring create object statement bean , Just tell spring To create an object of a class id:Custom name and unique value of the object. spring Find the object by this name class:The fully qualified name of the class (cannot be an interface because spring Is a reflection mechanism to create an object, you must use a class) spring It's done SomeService someService = new SomeServiceImpl(); spring Is to put the created object into map In, spring The frame has a map To store objects. springMap.put(id Value of, object); for example springMap.put("someService", new SomeServiceImpl()); One bean Label declares an object. --> <bean id="someService" class="com.jjh.service.impl.SomeServiceImpl" /> <bean id="someService1" class="com.jjh.service.impl.SomeServiceImpl" scope="prototype"/>
Use of test class (1)
@Test public void test01(){ SomeService service = new SomeServiceImpl(); service.doSome(); }
Use of test class (2)
@Test public void test03(){ String config="beans.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(config); //Use the method provided by spring to get the number of objects defined in the container int nums = ac.getBeanDefinitionCount(); System.out.println("Number of objects defined in container:"+nums); //The name of each defined object in the container String names [] = ac.getBeanDefinitionNames(); for(String name:names){ System.out.println(name); } }
1.4 XML based DI
1.4.1 set injection (key)
Set injection, also known as set value injection, refers to passing in the instance of the callee through the setter method. This injection method is simple and intuitive, so it is widely used in Spring dependency injection.
<?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 student object Injection: it means assignment Simple type: spring Specified in java Basic data types and String Are simple types. di:Assign values to attributes 1. set Injection (set value injection): spring Calling class set Method, you can set Method 1)Simple type set injection <bean id="xx" class="yyy"> <property name="Attribute name" value="The value of this property"/> One property Only one property can be assigned a value <property....> </bean> 2) Of reference type set Injection: spring Calling class set method <bean id="xxx" class="yyy"> <property name="Attribute name" ref="bean of id(The name of the object)" /> </bean> --> <bean id="myStudent" class="com.jjh.ba02.Student" > <property name="name" value="Li Si" /> <property name="age" value="26" /> <!--reference type--> <property name="school" ref="mySchool" /><!--setSchool(mySchool)--> </bean> <!--statement School object--> <bean id="mySchool" class="com.jjh.ba02.School"> <property name="name" value="Peking University"/> <property name="address" value="Haidian District " /> </bean> </beans>
1.4.2 structural injection
Construction injection refers to completing the instantiation of the callee while constructing the caller instance. That is, use the constructor to set dependencies.
<!-- 2.Structural injection: spring The calling class has a parameter construction method. While creating the object, assign a value to the attribute in the construction method. Construction injection usage <constructor-arg> label <constructor-arg> Label: one<constructor-arg>Represents a parameter of the construction method. <constructor-arg> Label properties: name:The formal parameter name that represents the constructor index:Indicates the position of the parameters of the construction method. The position of the parameters from left to right is the order of 0, 1 and 2 value: The formal parameter type of the constructor is a simple type. Use value ref: The formal parameter type of the constructor is a reference type. Use ref --> <!--use name Property to implement construct injection--> <bean id="myStudent" class="com.jjh.ba03.Student" > <constructor-arg name="myage" value="20" /> <constructor-arg name="mySchool" ref="myXueXiao" /> <constructor-arg name="myname" value="Zhou Liang"/> </bean> <!--use index attribute--> <bean id="myStudent2" class="com.jjh.ba03.Student"> <constructor-arg index="1" value="22" /> <constructor-arg index="0" value="Li Si" /> <constructor-arg index="2" ref="myXueXiao" /> </bean> <!--ellipsis index--> <bean id="myStudent3" class="com.jjh.ba03.Student"> <constructor-arg value="Qiang Qiang Zhang" /> <constructor-arg value="22" /> <constructor-arg ref="myXueXiao" /> </bean>
1.4.3 reference type automatic injection
- Byname (injected by name)
The attribute name of the reference type in the java class is the same as the id name of < bean > in the spring container (configuration file), and the data type is consistent. For beans in such a container, spring can assign values to the reference type.
<!-- Syntax: <bean id="xx" class="yyy" autowire="byName"> Simple type attribute assignment </bean> --> <bean id="myStudent" class="com.jjh.ba04.Student" autowire="byName"> <property name="name" value="Li Si" /> <property name="age" value="26" /> <!--reference type--> <!--<property name="school" ref="mySchool" />--> </bean> <!--statement School object--> <bean id="school" class="com.jjh.ba04.School"> <property name="name" value="Tsinghua University"/> <property name="address" value="Haidian District " /> </bean>
- Bytype (injected by type)
The data type of the reference type in the java class and the class attribute in the spring container (configuration file) are homologous. Such bean s can be assigned to the reference type
<!-- Syntax: <bean id="xx" class="yyy" autowire="byType"> Simple type attribute assignment </bean> Note: in byType In, in xml Declared in configuration file bean Only one qualified, The extra one is wrong --> <!--byType--> <bean id="myStudent" class="com.jjh.ba05.Student" autowire="byType"> <property name="name" value="Zhang SA" /> <property name="age" value="26" /> <!--reference type--> <!--<property name="school" ref="mySchool" />--> </bean> <!--statement School object--> <bean id="mySchool" class="com.jjh.ba05.School"> <property name="name" value="Renmin University of China"/> <property name="address" value="Haidian District " /> </bean>
1.4.4 configuration with Association
Configuration file for student class
<!--student modular bean statement--> <bean id="myStudent" class="com.jjh.domain.entity.Student" autowire="byType"> <property name="name" value="Zhang San"/> <property name="age" value="23"/> <!--Reference type data--> </bean>
Configuration file of School class
<bean id="mySchool" class="com.jjh.domain.entity.School"> <property name="address" value="Songpan"/> <property name="name" value="workers' university"/> </bean>
total profile
<!-- Profiles containing relationships: spring-total Indicates the main configuration file: if there are other configuration files, the main configuration file generally does not define objects. Syntax:<import resource="Path to other configuration files" /> keyword:"classpath:" Represents a classpath( class Directory where the file is located), stay spring To specify the location of other files in the configuration file of, you need to use classpath,tell spring Where to load the read file. -->
<!-- Loading is a list of files -- >
<!--
<import resource="classpath:ba01/applicationContext01.xml" />
<import resource="classpath:ba01/applicationContext02.xml" />
-->
<!--
In the configuration file containing the relationship, you can use wildcard (*: indicates any character)
Note: the main configuration file name cannot be included in the range of wildcards (it cannot be called spring-total.xml)
-->
<!-- Import profile -- >
<import resource="classpath:ba01/applicationContext*"/>
#### 1.5 annotation based DI * **Constraint file for annotation configuration**
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.or...
http://www.springframework.or...
https://www.springframework.o...d">
< !-- Package to be scanned when spring creates container @ componentscan -- >
< context:component-scan base-package="com.jjh">
< /context:component-scan >
< /beans >
* **Entity class**
@Data
@Component("myStudent")
public class Student {
private String name;
private int age;
/ / reference type
private School school;
}
* **Call in test class**
@Test
public void demo01(){
String config = "applicationContext.xml";
ApplicationContext app = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student)app.getBean("myStudent");
System.out.println(myStudent);
}
**1.5.1 To use annotations** 1. join maven Dependence of spring-context,Before you join spring-context At the same time, join indirectly spring-aop Dependence on. Notes must be used spring-aop rely on 2. Add in class spring Annotations for (annotations for multiple different functions) 3. stay spring Add a component-scan Label of the component scanner, indicating the location of the annotation in your project
< !-- Declare the component scan, and the component is the java object
Base package: Specifies the package name of the annotation in your project.
Working mode of component scan: spring will scan and traverse the package specified by base package,
All classes in the package and sub package, find the annotation in the class, create objects according to the annotation function, or assign values to attributes.
The component scan tag is added, and the changes of the configuration file are as follows:
1. Add a new constraint file spring context xsd
2. Give the new constraint file a namespace name
-->
<context:component-scan base-package="com.jjh.ba01" />
**1.5.2 Multi annotation item hierarchy** 1. @Component: Creating an object is equivalent to<bean>Function of Properties: value Is the name of the object, that is bean of id Value, value The value of is unique, and the object is created throughout spring Just one in the container 2. @Repository((used above the persistence layer class) : Put on dao Above the implementation class of, it means to create dao Object, dao Object can access the database. 3. @Service(Used above business layer classes): Put on service On the implementation class of, create service Object, service The object is used for business processing and can have transaction and other functions. 4. @Controller(Used on the controller): It is placed on the controller (processor) class to create the controller object, which can accept the parameters submitted by the user and display the processing results of the request The usage and syntax of the above three annotations@Component same. Can create objects, but these three annotations have additional functions. **1.5.3 Assignment of simple types** @Value: Attribute assignment of simple type Properties: value yes String Type that represents the property value of a simple type Use location: 1.Above the attribute definition, there is no need to set Method, recommended. 2.stay set Above the method **configuration file**
<context:component-scan base-package="com.jjh"/>
<!-- Properties file for configuring properties -- >
<context:property-placeholder location="classpath:student.properties"/>
**properties file**
name=Dick
age=20
@Component("myStudent")
public class Student {
/ / @ Value("Li Si")
@ Value("${myname}") / / use the data in the property configuration file
private String name;
@ Value("${myage}") / / use the data in the property configuration file
private Integer age;
}
**1.5.4 Assignment of reference type** Default mode 1.@Autowired: spring The annotation provided by the framework implements the assignment of reference types 2.spring The reference type is assigned by annotation in. The automatic injection principle is used to support byName, byType 3.@Autowired:The default is byType Automatic injection 4.Use location: * Use on properties * stay set Method used above
@Component("myStudent")
public class Student {
@ Value("Li Si")
private String name;
@Value("20")
private Integer age;
@Autowired
private School school;
}
Assignment by name If you want to use byName mode: Add attribute@Autowired Attribute added above@Qualifier(value="bean of id") : Represents a with the specified name bean Complete assignment in
@Component("myStudent")
public class Student {
@ Value("Li Si")
private String name;
@Value("20")
private Integer age;
@Autowired
@Qualifier("mySchool")
private School school;
}
#### **1.5.5 required attribute of Autowired** required :It's a boolean Type, default true required=true: Indicates that the reference type assignment fails, the program reports an error and terminates the execution required=false: Reference type if the assignment fails, the program will execute normally, and the reference type is null #### **1.5.6 JDK annotation @ Resource automatic injection** 1.@Resource: come from jdk Notes in, spring The framework provides functional support for this annotation, which can be used to reference type assignment 2.The principle of automatic injection is also used, which supports byName,byType The default is byName 3.Use location: Above the attribute definition, there is no need to set Method, recommended stay set Above method 4.The default is byName: First use byName Automatic injection, if byName Assignment failed, use again byType 5.@Resource Use only byName Method, you need to add an attribute name,name The value of is bean of id((name) **appoint name** **@Component("myStudent") public class Student { @Value("Li Si" ) private String name; private Integer age; //Use byName only @Resource(name = "mySchool") private School school;** **Default configuration**
@Component("myStudent")
public class Student {
@ Value("Li Si")
private String name;
private Integer age;
/ / use byName only
@Resource
private School school;