Spring framework learning notes
Note download: power node official website
Video viewing address
https://www.bilibili.com/video/BV1nz4y1d7uy
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.
Spring container is a large factory, which is 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 of the object, unique value. 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 spring Method provided 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:Represents the position of the parameter of the construction method. The position of the parameter from left to right is 0 , 1 ,2 Order of 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
student Class configuration file <!--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" /> --> <!-- Wildcards can be used in configuration files that contain relationships(*: (represents any character) Note: the configuration file name of the master cannot be included in the range of wildcards (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.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--spring Packages to scan when creating containers @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 steps for using annotations
1. Add maven's dependency spring context. When you add spring context, you indirectly add spring AOP dependency. Spring AOP dependencies must be used to use annotations
2. Add spring annotations (annotations of multiple different functions) to the class
3. Add a label of component scan component scanner in the spring configuration file to indicate the position of annotation in your project
<!--Declaration component scanner(component-scan),Components are java object base-package: Specify the package name of the annotation in your project. component-scan operation mode: spring Scan traversal base-package Specified 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. Joined component-scan Tag, change of configuration file: 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 layering
1. @Component: creates an object, which is equivalent to the function of < bean >
Attribute: value is the name of the object, that is, the id value of the bean. The value is unique. The created object is one in the whole spring container
2. @Repository (used on the persistence layer class): it is placed on the implementation class of dao, indicating the creation of dao objects, which can access the database.
3. @ service (used above the business layer class): put it on the implementation class of service and create a service object. The service 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 syntax of the above three annotations is the same as @ Component. Can create objects, but these three annotations have additional functions.
1.5.3 assignment of simple types
@Value: property assignment of simple type
Attribute: value is of type String and represents the attribute value of simple type
Use position: 1 The set method is not required for attribute definitions. It is recommended.
2. Above the set method
configuration file
<context:component-scan base-package="com.jjh"/>
<!--Configuration properties properties file-->
<context:property-placeholder location="classpath:student.properties"/>
properties file
name=Dick age=20 Click and drag to move @Component("myStudent") public class Student { //@Value("Li Si" ) @Value("${myname}") //Use the data in the property profile private String name; @Value("${myage}") //Use the data in the property profile private Integer age; }
1.5.4 assignment of reference types
Default mode
1. @ Autowired: the annotation provided by the spring framework implements the assignment of reference types
2.spring assigns values to reference types through annotations, uses the principle of automatic injection, and supports byname and bytype
3.@Autowired: byType auto injection is used by default
4. Use position:
Use on properties
Used on the set method
@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:
Add @ Autowired to the attribute
Add @ Qualifier(value="bean id"): indicates that the bean with the specified name is used to complete the assignment
@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 is a boolean type. The default value is true
- required=true: indicates that the reference type assignment fails, the program reports an error, and the execution is terminated
- 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: it comes from the annotation in the jdk. The spring framework provides functional support for this annotation, which can be used to assign values to reference types
2. The principle of automatic injection is also used. byName is supported. byType is byName by default
3. Use position:
- The set method is not required for attribute definitions. It is recommended
- Above the set method
4. byName by default: byName is automatically injected first. If byName assignment fails, byType is used again
5.@Resource only uses byName. It needs to add an attribute name. The value of name is the id (name) of the bean
Specify name
@Component("myStudent") public class Student { @Value("Li Si" ) private String name; private Integer age; //Use only byName @Resource(name = "mySchool") private School school;
Default configuration
@Component("myStudent") public class Student { @Value("Li Si" ) private String name; private Integer age; //Use only byName @Resource private School school;