9. Get acquainted with Spring framework
This section mainly introduces the ecological environment and concepts of Spring framework. In addition, compared with the traditional methods of creating objects, it introduces the methods of IOC container creating objects through nonparametric construction and parametric construction, and briefly explains the creation of objects at the bottom of Spring.
1. Spring overview
What is spring? Spring is an enterprise level development framework and a software design level framework. Its advantage is that it can layer the application system, and developers can choose components independently. At present, spring has become the de facto industry standard for Java enterprise project development.
Spring has three core modules:
- The Spring Framework is the cornerstone of the whole spring ecology. Spring is commonly referred to as the Spring Framework.
- Spring Boot is a rapid development framework that automatically integrates various mainstream components;
- Spring Cloud is a framework that integrates common modules of distributed applications to quickly realize microservice application development.
Two core mechanisms of Spring
- IOC (control inversion) / di (dependency injection)
- AOP (aspect oriented programming)
From the perspective of development, we use the Spring framework with its IOC and AOP. IOC(Inversion of Control) is a typical factory mode. Objects are injected through the factory, and AOP(Aspect Oriented Programming) is the embodiment of the proxy mode.
Spring architecture
From the perspective of design pattern and data persistence, the components that developers can choose are as follows:
- MVC: Strut2,Spring MVC
- ORMapping: Hibernate,MyBatis,Spring Data,MyBatis Plus
Enterprise level project features:
- Large scale: large number of users, large data scale and many functional modules
- High performance and safety requirements
- Complex business
- Flexible and changeable
Advantages of Spring:
- Low intrusive design
- Independent of various application servers
- The dependency injection feature makes the component relationship transparent and reduces the coupling
- Aspect oriented programming allows centralized management of common tasks
- Good integration with third-party frameworks
2. Spring IOC
What is control reversal?
In traditional program development, when an object needs to be called, the caller usually creates the called instance, that is, the object is actively new by the caller. However, the work of creating objects in the Spring framework is no longer completed by the caller, but handed over to the IoC container for creation and then pushed to the caller. The whole process completes the inversion, so it is control inversion.
Create entity class Student:
package com.trainingl.entity; import lombok.Data; @Data public class Student { private Integer id; private String name; private Double score; }
Using the traditional development method, manually instantiate the object new Student();
package com.trainingl.test; import com.trainingl.entity.Student; public class Test { public static void main(String[] args) { Student student = new Student(); student.setId(1); student.setName("Zhang San"); student.setScore(85.5); System.out.println(student); /* Console printout: Student(id=1, name = Zhang San, score=85.5) */ } }
2.1 IOC container creation object
POM under Maven project Add Spring related dependencies to XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.trainingl</groupId> <artifactId>springPro</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--Spring Framework dependency--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.4.RELEASE</version> </dependency> <!--lombok The plug-in automatically generates entity classes GET,SET,toString And nonparametric structure--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies> </project>
Add management object information in the configuration file, configuration file in XML format, and the file name can be customized, such as creating the configuration file spring xml;
<?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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <!--Configure an object--> <bean id="student" class="com.trainingl.entity.Student"> <property name="id" value="1"></property> <property name="name" value="Zhang San"></property> <property name="score" value="85.5"></property> </bean> </beans>
Note: configure an object through the < bean > tag in the Spring IoC container, where id is used to obtain the identification of the object, and class is the template class for creating the object.
Call the API to get the object. Spring provides two ways to get the object: id or runtime class
① Get object by id
package com.trainingl.test; import com.trainingl.entity.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1. Load spring XML configuration file ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); //2. Get the object through the id value Student stu = (Student)applicationContext.getBean("student"); System.out.println(stu); } }
Print information for console:
Spring underlying parsing: first load spring.xml through XML parsing XML configuration file, then use the reflection mechanism to call the parameterless constructor to dynamically create the object, and call the setter method to complete the assignment of the object attribute. Finally, put the created object in a container similar to HashMap. When calling the getBean method to obtain the object, it is equivalent to map Get (ID) returns an object.
② Get objects through runtime classes
package com.trainingl.test; import com.trainingl.entity.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1. Load spring XML configuration file ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); //2. Get the object through the runtime class Student stu = (Student)applicationContext.getBean(Student.class); System.out.println(stu); } }
This method when spring When configuring two Student class beans in XML, the program will report an error because both beans are generated by the Student class. The IOC container cannot return both beans and must specify a unique bean. For example:
<?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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <bean id="student1" class="com.trainingl.entity.Student"> <property name="id" value="1"></property> <property name="name" value="Zhang San"></property> <property name="score" value="85.5"></property> </bean> <bean id="student2" class="com.trainingl.entity.Student"> <property name="id" value="1"></property> <property name="name" value="Zhang San"></property> <property name="score" value="85.5"></property> </bean> </beans>
The printed information of the console is as follows:
2.2 detailed description of configuration file
spring.xml
<!--Configure an object and omit header information--> <bean id="student" class="com.trainingl.entity.Student"> <property name="id" value="1"></property> <property name="name" value="Zhang San"></property> <property name="score" value="85.5"></property> </bean>
1. Manage objects by configuring bean tags;
- id: object identifier (unique);
- Class: the template class of the object (all classes managed by the IoC container must have construction methods, because when the Spring bottom layer creates the object through the reflection mechanism, it calls parameterless construction or parameterless construction);
2. The member variables of the object are assigned through the property tag;
- Name: member variable name;
- Value: value of member variable (basic data type and String type can be assigned directly. If they are other reference types, they cannot be assigned through value);
3. Create bean s through parameterized construction;
- The entity class must have a corresponding parameterized constructor, otherwise an error will be reported;
- Add parameter label < constructor Arg > < / constructor > to the configuration file
<bean id="student" class="com.trainingl.entity.Student"> <constructor-arg name="id" value="12"></constructor-arg> <constructor-arg name="name" value="Wang Wu"></constructor-arg> <constructor-arg name="score" value="85"></constructor-arg> </bean>
Different from the above configuration of nonparametric construction, when creating an object with parametric construction, the object is created and assigned while the nonparametric construction creates the object first, and then completes the attribute assignment through the setter method.
Of course, you can also change the order by indexing:
<bean id="student" class="com.trainingl.entity.Student"> <constructor-arg index="0" value="1"></constructor-arg> <constructor-arg index="2" value="85"></constructor-arg> <constructor-arg index="1" value="Wang Wu"></constructor-arg> </bean>
When using the Spring IoC container to create objects, whether to call the parameterless + setter method or the parameterless + setter method directly to create objects is only different in XML configuration. In addition, we must pay attention to: when using what method, we must ensure that the corresponding method exists. For example, if the XML file is constructed with full parameters to configure parameters, but there is no full parameter construction method in the entity class, an error will be reported.