Detailed summary of Spring documentation

Posted by walshd on Mon, 13 Sep 2021 02:37:04 +0200

Spring 5 framework

Course content introduction

1. Spring framework overview

2. IOC container

(1) IOC underlying principle
(2) IOC interface (BeanFactory) (3) IOC operation Bean Management (xml based) (4) IOC operation Bean Management (annotation based)

3,Aop

4,JdbcTemplate

5. Transaction management

6. What's new in spring 5

Spring 5 framework overview

1. Spring is a lightweight open source Java EE framework
2. Spring can solve the complexity of enterprise application development
3. Spring has two core parts: IOC and Aop
(1) IOC: inversion of control, leaving the process of creating objects to Spring for management
(2) Aop: aspect oriented, without modifying the source code for function enhancement
4. Spring features
(1) Convenient decoupling and simplified development
(2) Aop programming support
(3) Convenient program testing
(4) Facilitate integration with other frameworks
(5) Facilitate transaction operations
(6) Reduce the difficulty of API development
5. Now in the course, select Spring version 5.x
Introduction to spring 5
1. Download spring 5
(1) Use the latest stable version of Spring 5.2.6
(2) Download address
https://repo.spring.io/release/org/springframework/spring/
2. Open the idea tool to create a normal Java project
3. Import spring 5 related jar packages
4. Create a common class and create a common method in this class

public class User {
 public void add() {
 System.out.println("add......");
 } }

5. Create a Spring configuration file and configure the created object in the configuration file (1) the Spring configuration file uses xml format

<?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">
 <!--to configure User objects creating--> 
 <bean id="user" class="com.atguigu.spring5.User"></bean>
</beans> 

6. Write test code

@Test
public void testAdd() {
 //1 load spring configuration file
 ApplicationContext context =
 new ClassPathXmlApplicationContext("bean1.xml");
 //2 get the object created by configuration
 User user = context.getBean("user", User.class);
 System.out.println(user);
 user.add();
}

IOC (concept and principle)

1. What is IOC
(1) Control inversion, and leave the object creation and calling process between objects to Spring for management
(2) Purpose of using IOC: to reduce coupling
(3) An introductory case is IOC implementation
2. IOC underlying principle
(1) xml parsing, factory schema, reflection
3. Draw pictures to explain the underlying principle of IOC

IOC (BeanFactory interface)

1. The IOC idea is based on the IOC container, and the bottom layer of the IOC container is the object factory
2. Spring provides two ways to implement IOC container: (two interfaces)

(1) BeanFactory: the basic implementation of IOC container. It is the internal use interface of Spring and is not available for developers to use
*>The object will not be created when the configuration file is loaded. The object is created only after the object is obtained (used)
(2) ApplicationContext: the sub interface of BeanFactory interface, which provides more and more powerful functions. It is generally used by developers
Use by the operator

  • When the configuration file is loaded, the configuration file object will be created
    3. The ApplicationContext interface has implementation classes

IOC operation Bean Management (concept)

1. What is Bean management
(0) Bean management refers to two operations
(1) Spring create object
(2) Spirng injection properties
2. There are two ways to manage Bean operations
(1) Implementation of configuration file based on xml
(2) Annotation based implementation

IOC operation Bean Management (based on xml)

1. Creating objects based on xml

(1) In the spring configuration file, you can create objects by using bean tags and adding corresponding attributes to the tags
(2) There are many properties in the bean tag. Introduce the common properties

  • id attribute: unique identification
  • Class attribute: class full path (package class path)
    (3) When creating an object, the default is to execute the parameterless construction method to complete the object creation

2. Attribute injection based on xml

(1) DI: dependency injection is the injection attribute

3. The first injection method: use the set method for injection

(1) Create a class, define properties and corresponding set methods

/**
* Demonstrates using the set method to inject attributes
*/
public class Book {
 //Create attribute
 private String bname;
 private String bauthor;
 //Create the set method corresponding to the property
 public void setBname(String bname) {
 this.bname = bname;
 }
 public void setBauthor(String bauthor) {
 this.bauthor = bauthor;
 } }

(2) Create a configuration object in the spring configuration file and configure attribute injection

<!--2 set Method injection properties--> <bean id="book" class="com.atguigu.spring5.Book">
 <!--use property Complete attribute injection
 name: Attribute name in class
 value: Values injected into attributes
 -->
 <property name="bname" value="Yi Jin Jing"></property>
 <property name="bauthor" value="Dharma ancestor"></property>
</bean> 

4. The second injection method: injection with parameter structure

(1) Create a class and define an attribute. The created attribute corresponds to a parameter construction method

/**
* Construct injection with parameters
*/
public class Orders {
 //attribute
 private String oname;
 private String address;
 //Parametric construction
 public Orders(String oname,String address) {
 this.oname = oname;
 this.address = address;
 } }

(2) Configure in the spring configuration file

<!--3 Injection attribute with parameter construction--> <bean id="orders" class="com.atguigu.spring5.Orders">
 <constructor-arg name="oname" value="computer"></constructor-arg>
 <constructor-arg name="address" value="China"></constructor-arg>
</bean> 

5. p namespace injection (understand)

(1) Using p namespace injection can simplify xml based configuration
The first step is to add the p namespace in the configuration file
The second step is property injection, which operates in the bean tag

<!--2 set Method injection properties--> <bean id="book" class="com.atguigu.spring5.Book" p:bname="nine men's power" 
p:bauthor="anonymous person"></bean>

IOC operation Bean Management (xml injection and other types of attributes)

1. Literal quantity

(1) null value

<!--null value--> <property name="address">
 <null/>
</property> (2)Attribute values contain special symbols
<!--Attribute values contain special symbols
 1 hold<>Escape &lt; &gt;
 2 Write content with special symbols to CDATA
--><property name="address">
 <value><![CDATA[<<Nanjing>>]]></value>
</property> 

2. Injection properties - External bean s

(1) Create two classes, service class and dao class. (2) call the methods in dao in service
(3) Configure in the spring configuration file

public class UserService {
 //Create UserDao type attribute and generate set method
 private UserDao userDao;
 public void setUserDao(UserDao userDao) {
 this.userDao = userDao;
 }
 public void add() {
 System.out.println("service add...............");
 userDao.update();
 } }
<!--1 service and dao objects creating--> <bean id="userService" class="com.atguigu.spring5.service.UserService">
 <!--injection userDao object
 name Attribute: the name of the attribute in the class
 ref Properties: Creating userDao object bean label id value
 -->
 <property name="userDao" ref="userDaoImpl"></property>
</bean> <bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean> 

3. Injection properties - internal bean s

(1) One to many relationships: departments and employees
A department has multiple employees, and one employee belongs to one department
The Department is one, and there are many employees
(2) One to many relationships are represented between entity classes. Employees represent their departments and are represented by object type attributes

//Department category
public class Dept {
 private String dname;
 public void setDname(String dname) {
 this.dname = dname;
 } }
//Employee category
public class Emp {
 private String ename;
 private String gender;
 //Employees belong to a department and are represented in object form
 private Dept dept;
 public void setDept(Dept dept) {
 this.dept = dept;
 }
 public void setEname(String ename) {
 this.ename = ename;
 }
 public void setGender(String gender) {
 this.gender = gender;
 } }

(3) Configure in the spring configuration file

<!--inside bean--> <bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--Set two common properties-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="female"></property>
 <!--Set object type properties-->
 <property name="dept">
 <bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="Security Department"></property>
 </bean>
 </property>
</bean> 

4. Injection attribute - cascade assignment (1) the first writing method

<!--Cascade assignment--> <bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--Set two common properties-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="female"></property>
 <!--Cascade assignment-->
 <property name="dept" ref="dept"></property>
</bean> <bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="Finance Department"></property>
</bean> (2)The second way to write
<!--Cascade assignment--> <bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--Set two common properties-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="female"></property>
 <!--Cascade assignment-->
 <property name="dept" ref="dept"></property>
 <property name="dept.dname" value="Technology Department"></property>
</bean> <bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="Finance Department"></property>
</bean>

IOC operation Bean Management (xml injection collection attribute)

1. Inject array type properties
2. Inject List collection type properties
3. Inject Map collection type properties
(1) Create classes, define array, list, map and set type attributes, and generate corresponding set methods

public class Stu {
 //1 array type properties
 private String[] courses;
 //2 list collection type attribute
 private List<String> list;
 //3 map collection type attribute
 private Map<String,String> maps;
 //4 set set type attribute
 private Set<String> sets;
 public void setSets(Set<String> sets) {
 this.sets = sets;
 }
 public void setCourses(String[] courses) {
 this.courses = courses;
 }
 public void setList(List<String> list) {
 this.list = list;
 }
 public void setMaps(Map<String, String> maps) {
 this.maps = maps;
 } }

(2) Configure in the spring configuration file

<!--1 Collection type attribute injection--> <bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">
 <!--Array type attribute injection-->
 <property name="courses">
 <array>
 <value>java curriculum</value>
 <value>Database course</value>
 </array>
 </property>
 <!--list Type attribute injection-->
 <property name="list">
 <list>
 <value>Zhang San</value>
 <value>the other woman</value>
 </list>
 </property>
 <!--map Type attribute injection-->
 <property name="maps">
 <map>
 <entry key="JAVA" value="java"></entry>
 <entry key="PHP" value="php"></entry>
 </map>
 </property>
 <!--set Type attribute injection-->
 <property name="sets">
 <set>
 <value>MySQL</value>
 <value>Redis</value>
 </set>
 </property>
</bean> 

4. Set the object type value in the collection

<!--Create multiple course object--> <bean id="course1" class="com.atguigu.spring5.collectiontype.Course">
 <property name="cname" value="Spring5 frame"></property>
</bean> <bean id="course2" class="com.atguigu.spring5.collectiontype.Course">
 <property name="cname" value="MyBatis frame"></property>
</bean>
<!--injection list Collection type, value is object--> <property name="courseList">
 <list>
 <ref bean="course1"></ref>
 <ref bean="course2"></ref>
 </list>
</property> 

5. Extract the set injection part

(1) Introducing the namespace util into the spring 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"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/util 
http://Www.springframework. Org / schema / util / spring util. XSD "> (2) use util tag to complete list collection injection and extraction
<!--1 extract list Collection type attribute injection--> <util:list id="bookList">
 <value>Yi Jin Jing</value>
 <value>Jiu Yin Zhen Jing</value>
 <value>nine men's power</value>
</util:list>
<!--2 extract list Collection type attribute injection usage--> <bean id="book" class="com.atguigu.spring5.collectiontype.Book">
 <property name="list" ref="bookList"></property>
</bean>

IOC operation Bean Management (FactoryBean)

1. Spring has two types of beans, a normal bean and a factory bean

2. Ordinary bean: the bean type defined in the configuration file is the return type

3. Factory bean: the bean type defined in the configuration file can be different from the return type

The first step is to create a class that acts as a factory bean and implements the interface FactoryBean
The second step is to implement the method in the interface and define the returned bean type in the implemented method

public class MyBean implements FactoryBean<Course> {
 //Define return bean
 @Override
 public Course getObject() throws Exception {
 Course course = new Course();
 course.setCname("abc");
 return course;
 }
 @Override
 public Class<?> getObjectType() {
 return null;
 }
 @Override
 public boolean isSingleton() {
 return false;
 } }
 <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
</bean>
@Test
public void test3() {
 ApplicationContext context =
 new ClassPathXmlApplicationContext("bean3.xml");
 Course course = context.getBean("myBean", Course.class);
 System.out.println(course);
}

IOC operation bean Management (bean scope)

1. In Spring, set whether to create a bean instance as a single instance or multiple instances
2. In Spring, by default, bean s are single instance objects
3. How to set single instance or multi instance
(1) In the bean tag of spring configuration file, there is a property (scope) to set single instance or multiple instances
(2) scope property value
The first value is the default value, singleton, which indicates that it is a single instance object
The second value, prototype, represents a multi instance object
(3) The difference between singleton and prototype
The first is singleton single instance and prototype multi instance
Second, when the scope value is set to singleton, a single instance object will be created when the spring configuration file is loaded
When you set the scope value to prototype, instead of creating an object when loading the spring configuration file, you call
Create a multi instance object when using the getBean method
IOC operation bean Management (bean lifecycle)

1. Life cycle

(1) The process from object creation to object destruction

2. bean lifecycle

(1) Create bean instance through constructor (no parameter construction)
(2) Set values for bean properties and references to other beans (call the set method)
(3) Call the initialization method of the bean (the method that needs configuration initialization)
(4) The bean is ready to use (the object is obtained)
(5) When the container is closed, call the bean destruction method (the method that needs to be configured for destruction)

3. Demonstrates the bean lifecycle

public class Orders {
 //Nonparametric construction
 public Orders() {
 System.out.println("The first step is to create a parameterless construction bean example");
 }
 private String oname;
 public void setOname(String oname) {
 this.oname = oname;
 System.out.println("Step 2 call set Method to set the property value");
 }
 //Method for creating and executing initialization
 public void initMethod() {
 System.out.println("Step 3: execute initialization method");
 }
 //Method for creating and executing destruction
 public void destroyMethod() {
 System.out.println("Step 5 method of destruction");
 } }
 <bean id="orders" class="com.atguigu.spring5.bean.Orders" initmethod="initMethod" destroy-method="destroyMethod">
 <property name="oname" value="mobile phone"></property>
</bean>
 @Test
 public void testBean3() {
// ApplicationContext context =
// new ClassPathXmlApplicationContext("bean4.xml");
 ClassPathXmlApplicationContext context =
 new ClassPathXmlApplicationContext("bean4.xml");
 Orders orders = context.getBean("orders", Orders.class);
 System.out.println("Step 4 get and create bean Instance object");
 System.out.println(orders);
 //Manually destroy the bean instance
 context.close();
 } 

4. The post processor of a bean. The bean life cycle has seven steps

(1) Create bean instance through constructor (no parameter construction)
(2) Set values for bean properties and references to other beans (call the set method)
(3) Pass the bean instance to the bean post processor method postProcessBeforeInitialization (4) and call the bean initialization method (the method that needs configuration initialization)
(5) Pass the bean instance to the bean post processor method postProcessAfterInitialization
(6) The bean is ready to use (the object is obtained)
(7) When the container is closed, call the bean destruction method (the method that needs to be configured for destruction)

5. Demonstrate the effect of adding a post processor

(1) Create a class, implement the interface BeanPostProcessor, and create a post processor

public class MyBeanPost implements BeanPostProcessor {
 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName) 
throws BeansException {
 System.out.println("Method executed before initialization");
 return bean;
 }
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) 
throws BeansException {
 System.out.println("Method executed after initialization");
 return bean;
 } }
<!--Configure post processor--> <bean id="myBeanPost" class="com.atguigu.spring5.bean.MyBeanPost"></bean>

IOC operation Bean Management (xml Automatic Assembly)

1. What is automatic assembly
(1) According to the specified assembly rules (attribute name or attribute type), Spring automatically injects the matching attribute values
2. Demonstrate the automatic assembly process
(1) Auto injection based on attribute name

<!--Realize automatic assembly
 bean Label properties autowire,Configure auto assembly
 autowire Property has two common values:
 byName Inject value according to attribute name bean of id The value is the same as the class attribute name
 byType Injection according to attribute type
--><bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">
 <!--<property name="dept" ref="dept"></property>-->
</bean> <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

(2) Auto injection based on attribute type

<!--Realize automatic assembly
 bean Label properties autowire,Configure auto assembly
 autowire Property has two common values:
 byName Inject value according to attribute name bean of id The value is the same as the class attribute name
 byType Injection according to attribute type
--><bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">
 <!--<property name="dept" ref="dept"></property>-->
</bean> <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

IOC operation Bean Management (external property file) 1. Directly configure database information

(1) Configure Druid connection pool
(2) Introducing Druid connection pool dependent jar package

<!--Configure connection pool directly--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
 <property name="url" 
value="jdbc:mysql://localhost:3306/userDb"></property>
 <property name="username" value="root"></property>
 <property name="password" value="root"></property>
</bean>

2. Importing an external property file to configure the database connection pool

(1) Create external property files, properties format files, and write database information
(2) Import the external properties property file into the spring configuration file

  • Introducing context namespace
<beans xmlns="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:util="http://www.springframework.org/schema/util" 
 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/util 
http://www.springframework.org/schema/util/spring-util.xsd 
 http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd">  ⚫  Using tags to import external property files in spring configuration files
<!--Import external properties file--> <context:property-placeholder location="classpath:jdbc.properties"/>
<!--Configure connection pool--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
 <property name="driverClassName" value="${prop.driverClass}"></property>
 <property name="url" value="${prop.url}"></property>
 <property name="username" value="${prop.userName}"></property>
 <property name="password" value="${prop.password}"></property>
</bean>

IOC operation Bean Management (annotation based method) 1. What is annotation

(1) Annotation is a code special tag, format: @ annotation name (attribute name = attribute value, attribute name = attribute value...)
(2) Using annotations, annotations act on classes, methods and properties
(3) Purpose of using annotations: to simplify xml configuration
2. Spring provides annotations for creating objects in Bean management
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository

  • The above four annotation functions are the same and can be used to create bean instances
    3. Object creation based on annotation
    Step 1: introduce dependency
    Step 2 start component scanning
<!--Turn on component scanning
 1 If multiple packages are scanned, they are separated by commas
 2 Scan package upper directory
--><context:component-scan base-package="com.atguigu"></context:component-scan>

The third step is to create a class and add the creation object annotation on the class

//In the annotation, the value attribute value can be omitted,
//The default value is the class name, which is lowercase
//UserService -- userService
@Component(value = "userService") //<bean id="userService" class=".."/>
public class UserService {
 public void add() {
 System.out.println("service add.......");
 } }

4. Enable component scanning details configuration

<!--Example 1
 use-default-filters="false" Indicates that the default is not used now filter,Self configuration filter
 context:include-filter ,Set what to scan
--><context:component-scan base-package="com.atguigu" use-defaultfilters="false">
 <context:include-filter type="annotation" 
 
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--Example 2
 Next, configure all contents of the scanning package
 context:exclude-filter:  Set what is not scanned
--><context:component-scan base-package="com.atguigu">
 <context:exclude-filter type="annotation" 
 
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

5. Attribute injection based on annotation
(1) @ Autowired: auto assemble according to attribute type
The first step is to create the service and dao objects, and add the creation object annotation in the service and dao classes
The second step is to inject dao objects into the service, add dao type attributes to the service class, and use annotations on the attributes

@Service
public class UserService {
 //Define dao type properties
 //There is no need to add a set method
 //Add injection attribute annotation
 @Autowired 
 private UserDao userDao;
 public void add() {
 System.out.println("service add.......");
 userDao.add();
 } }

(2) @ Qualifier: inject by name
The @ Qualifier annotation is used together with @ Autowired above

//Define dao type properties
//There is no need to add a set method
//Add injection attribute annotation
@Autowired //Injection according to type
@Qualifier(value = "userDaoImpl1") //Injection by name
private UserDao userDao; 

(3) @ Resource: can be injected according to type or name

//@Resource / / inject according to type
@Resource(name = "userDaoImpl1") //Injection by name
private UserDao userDao; 

(4) @ Value: inject common type attribute

@Value(value = "abc")
private String name;

6. Fully annotated development
(1) Create a configuration class to replace the xml configuration file

@Configuration //As a configuration class, replace the xml configuration file
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {
}

(2) Writing test classes

@Test
public void testService2() {
 //Load configuration class
 ApplicationContext context
 = new AnnotationConfigApplicationContext(SpringConfig.class);
 UserService userService = context.getBean("userService", 
UserService.class);
 System.out.println(userService);
 userService.add();
}

AOP (concept)

1. What is AOP

(1) Aspect oriented programming (aspect oriented), AOP can isolate all parts of business logic, so as to make
The coupling degree between various parts of business logic is reduced, the reusability of the program is improved, and the development efficiency is improved.
(2) Popular Description: add new functions to the main functions without modifying the source code
(3) Use the login example to illustrate AOP

AOP (underlying principle)

1. The underlying AOP uses dynamic proxies

(1) There are two cases of dynamic agents
In the first case, JDK dynamic proxy is used
⚫ Create an interface to implement class proxy objects and enhance class methods
In the second case, CGLIB dynamic proxy is used
⚫ Create the proxy object of the subclass and enhance the method of the class

AOP (JDK dynamic agent)

1. Use JDK dynamic Proxy and use the methods in the Proxy class to create Proxy objects

(1) Call the newProxyInstance method
Method has three parameters:
First parameter, class loader
The second parameter is the class where the enhancement method is located. The interface implemented by this class supports multiple interfaces
The third parameter is to implement this interface InvocationHandler, create a proxy object and write the enhanced part

2. Write JDK dynamic agent code

(1) Create interfaces and define methods

public interface UserDao {
 public int add(int a,int b);
 public String update(String id);
}

(2) Create interface implementation classes and implement methods

public class UserDaoImpl implements UserDao {
 @Override
 public int add(int a, int b) {
 return a+b;
 }
 @Override
 public String update(String id) {
 return id;
 } }

(3) Creating interface Proxy objects using Proxy classes

public class JDKProxy {
 public static void main(String[] args) {
 //Create interface implementation class proxy object
 Class[] interfaces = {UserDao.class};
// Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, 
new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) 
throws Throwable {
// return null;
// }
// });
 UserDaoImpl userDao = new UserDaoImpl();
 UserDao dao = 
(UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, 
new UserDaoProxy(userDao));
 int result = dao.add(1, 2);
 System.out.println("result:"+result);
 } }
//Create proxy object code
class UserDaoProxy implements InvocationHandler {
 //1. Who is the proxy object created and who is passed over
 //Parametric construction transfer
 private Object obj;
 public UserDaoProxy(Object obj) {
 this.obj = obj;
 }
 //Enhanced logic
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws 
Throwable {
 //Before method
 System.out.println("Method...."+method.getName()+" :Passed parameters
 number..."+ Arrays.toString(args));
 //Enhanced method execution
 Object res = method.invoke(obj, args);
 //After method
 System.out.println("Method...."+obj);
 return res;
 } }

AOP (terminology)

1. Connection point
2. Entry point
3. Notification (enhanced)
4. Section

AOP operation (preparatory work)

1. Spring frameworks generally implement AOP operations based on AspectJ

(1) AspectJ is not a part of Spring. It is an independent AOP framework. Generally, AspectJ and Spirng framework are used together
AOP operation with

2. Implementation of AOP operation based on AspectJ

(1) Implementation of configuration file based on xml
(2) Annotation based implementation (use)

3. Introduce AOP related dependencies into the project

4. Pointcut expression

(1) Pointcut expression function: know which method in which class to enhance
(2) Syntax structure:

 execution([Permission modifier] [Return type] [Class full path] [Method name]([parameter list]) )
Example 1: Yes com.atguigu.dao.BookDao Class add Enhance
execution(* com.atguigu.dao.BookDao.add(..))
Example 2: Yes com.atguigu.dao.BookDao Class
execution(* com.atguigu.dao.BookDao.* (..))
Example 3: Yes com.atguigu.dao All classes in the package and all methods in the class are enhanced
execution(* com.atguigu.dao.*.* (..))

AOP operation (AspectJ annotation)

1. Create a class and define methods in the class

public class User {
 public void add() {
 System.out.println("add.......");
 } }

2. Create enhancement classes (write enhancement logic)
(1) In the enhanced class, create methods so that different methods represent different notification types

//Enhanced class
public class UserProxy {
 public void before() {//Before advice 
 System.out.println("before......");
 } }

3. Configure notifications
(1) In the spring configuration file, turn on annotation scanning

<?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:aop="http://www.springframework.org/schema/aop" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd 
 http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd">
 <!-- Enable annotation scanning -->
 <context:component-scan basepackage="com.atguigu.spring5.aopanno"></context:component-scan> 

(2) Creating User and UserProxy objects using annotations
(3) Add the annotation @ Aspect on the enhanced class

//Enhanced class
@Component
@Aspect //Generate proxy object
public class UserProxy {}

(4) Turn on the build proxy object in the spring configuration file

<!-- open Aspect Generate proxy object--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 

4. Configure different types of notifications
(1) In the enhanced class, add the notification type annotation on the notification method, and use the pointcut expression configuration

//Enhanced class
@Component
@Aspect //Generate proxy object
public class UserProxy {
 //Before advice 
 //@The Before annotation indicates as a pre notification
 @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void before() {
 System.out.println("before.........");
 }
 //Post notification (return notification)
 @AfterReturning(value = "execution(* 
com.atguigu.spring5.aopanno.User.add(..))")
 public void afterReturning() {
 System.out.println("afterReturning.........");
 }
 //Final notice
 @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void after() {
 System.out.println("after.........");
 }
 //Exception notification
 @AfterThrowing(value = "execution(* 
com.atguigu.spring5.aopanno.User.add(..))")
 public void afterThrowing() {
 System.out.println("afterThrowing.........");
 }
 //Around Advice 
 @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void around(ProceedingJoinPoint proceedingJoinPoint) throws 
Throwable {
 System.out.println("Before surround.........");
 //Enhanced method execution
 proceedingJoinPoint.proceed();
 System.out.println("After surround.........");
 } }

5. Same pointcut extraction

//Same pointcut extraction
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void pointdemo() {
}
//Before advice 
//@The Before annotation indicates as a pre notification
@Before(value = "pointdemo()")
public void before() {
 System.out.println("before.........");
}

6. Multiple enhancement classes can be enhanced by the same method, and the priority of enhancement classes can be set
(1) Add the annotation @ order (numeric type value) on the enhanced class. The smaller the numeric type value, the higher the priority

@Component
@Aspect
@Order(1)
public class PersonProxy

7. Full use of annotation development
(1) To create a configuration class, you do not need to create an xml configuration file

@Configuration
@ComponentScan(basePackages = {"com.atguigu"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

AOP operation (AspectJ configuration file)

1. Create two classes, enhanced class and enhanced class, and create methods
2. Create two class objects in the spring configuration file

<!--create object--> <bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean> <bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean> 3,stay spring Configure pointcuts in configuration files
<!--to configure aop enhance--> <aop:config>
 <!--breakthrough point-->
 <aop:pointcut id="p" expression="execution(* 
com.atguigu.spring5.aopxml.Book.buy(..))"/>
 <!--Configure section-->
 <aop:aspect ref="bookProxy">
 <!--The enhancement effect is on the specific method-->
 <aop:before method="before" pointcut-ref="p"/>
 </aop:aspect>
</aop:config>

Transaction operation (transaction concept)

1. What business

(1) Transaction is the most basic unit of database operation. Logically, a group of operations either succeed or all operations fail
All failed
(2) Typical scenario: bank transfer

  • lucy transfers 100 yuan to mary
  • lucy is 100 less and mary is 100 more

2. Transaction four characteristics (ACID) (1) atomicity

(2) Consistency
(3) Isolation
(4) Persistence

Transaction operation (build transaction operation environment)

1. Create database tables and add records

2. Create a service, build a dao, and complete the object creation and injection relationship

(1) service is injected into dao, JdbcTemplate is injected into dao, and DataSource is injected into JdbcTemplate

@Service
public class UserService {
 //Injection dao
 @Autowired
 private UserDao userDao; }
@Repository
public class UserDaoImpl implements UserDao {
 @Autowired
 private JdbcTemplate jdbcTemplate; }3,stay dao Create two methods: more money and less money service Creation method (method of transfer)
@Repository
public class UserDaoImpl implements UserDao {
 @Autowired
 private JdbcTemplate jdbcTemplate;
 //lucy transfers 100 to mary
 //Less money
 @Override
 public void reduceMoney() {
 String sql = "update t_account set money=money-? where username=?";
 jdbcTemplate.update(sql,100,"lucy");
 }
 //More money
 @Override
 public void addMoney() {
 String sql = "update t_account set money=money+? where username=?";
 jdbcTemplate.update(sql,100,"mary");
 } }
@Service
public class UserService {
 //Injection dao
 @Autowired
 private UserDao userDao;
 //Method of transfer
 public void accountMoney() {
 //lucy less than 100
 userDao.reduceMoney();
 //mary more than 100
 userDao.addMoney();
 } }

4. If the above code is executed normally, there is no problem, but if an exception occurs during code execution, there is a problem

(1) How to solve the above problems?

  • Use transactions for resolution
    (2) Transaction operation process

Transaction operation (Introduction to Spring transaction management)

1. Transactions are added to the Service layer (business logic layer) in the three-tier structure of Java EE

2. Transaction management operations in Spring

(1) There are two ways: programmatic transaction management and declarative transaction management (using)

3. Declarative transaction management

(1) Annotation based approach (use)
(2) xml based configuration file mode

4. For declarative transaction management in Spring, the underlying layer uses AOP principle

5. Spring Transaction Management API

(1) An interface is provided to represent the transaction manager. This interface provides different implementation classes for different frameworks

Transaction operations (annotated declarative transaction management)

1. Configure the transaction manager in the spring configuration file

<!--Create transaction manager--> <bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--Injection data source-->
 <property name="dataSource" ref="dataSource"></property>
</bean>

2. In the spring configuration file, open the transaction annotation

(1) Introducing the namespace tx into the spring configuration file

<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:aop="http://www.springframework.org/schema/aop" 
 xmlns:tx="http://www.springframework.org/schema/tx" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd 
 http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd 
 http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd"> 

(2) Open transaction annotation

`<!--Open transaction annotation--> <tx:annotation-driven transactionmanager="transactionManager"></tx:annotation-driven>` 

3. Add transaction annotations on the service class (or on the methods in the service class)

(1) @ Transactional, this annotation can be added to classes or methods
(2) If you add this annotation to the class, all the methods in the class will add transactions
(3) If you add this annotation to the method, add transactions for the method

@Service
@Transactional
public class UserService {}

Transaction operation (declarative transaction management parameter configuration)

1. Add the annotation @ Transactional on the service class, in which transaction related parameters can be configured

2. Propagation: transaction propagation behavior

(1) Multiple transaction methods are called directly. How are transactions managed in this process

3. ioslation: transaction isolation level

(1) Transactions have the characteristic of isolation, and multi transaction operations will not have an impact. There are many problems without considering isolation
(2) There are three reading problems: dirty reading, unrepeatable reading and virtual (illusory) reading
(3) Dirty read: data read from one uncommitted transaction to another uncommitted transaction
(4) Non repeatable read: one uncommitted transaction reads the modified data from another committed transaction
(5) Virtual read: an uncommitted transaction reads and adds data to another committed transaction
(6) Solution: solve the read problem by setting the transaction isolation level

4. Timeout: timeout

(1) The transaction needs to be committed within a certain period of time. If it is not committed, it will be rolled back
(2) The default value is - 1, and the set time is calculated in seconds

5. readOnly: read only

(1) Read: query, write: add, modify, delete
(2) The default value of readOnly is false, which means that you can query, add, modify and delete operations
(3) Set the readOnly value to true. After it is set to true, you can only query

6. Rollback for: rollback

(1) Set which exceptions occur for transaction rollback

7. noRollbackFor: do not rollback

(1) Set which exceptions occur without transaction rollback
Transaction operations (XML declarative transaction management)
1. Configure in the spring configuration file
Step 1: configure the transaction manager
Step 2 configure notifications
Step 3 configure pointcuts and facets

<!--1 Create transaction manager--> <bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--Injection data source-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 Configure notifications--> <tx:advice id="txadvice">
 <!--Configure transaction parameters-->
 <tx:attributes>
 <!--Specify which rule method to add transactions to-->
 <tx:method name="accountMoney" propagation="REQUIRED"/>
 <!--<tx:method name="account*"/>-->
 </tx:attributes>
</tx:advice>
<!--3 Configure pointcuts and facets--> <aop:config>
 <!--Configure pointcuts-->
 <aop:pointcut id="pt" expression="execution(* 
com.atguigu.spring5.service.UserService.*(..))"/>
 <!--Configure section-->
 <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

Transaction operations (fully annotated declarative transaction management)

1. Create a configuration class and use the configuration class instead of the xml configuration file

@Configuration //Configuration class
@ComponentScan(basePackages = "com.atguigu") //Component scan
@EnableTransactionManagement //Open transaction
public class TxConfig {
 //Create database connection pool
 @Bean
 public DruidDataSource getDruidDataSource() {
 DruidDataSource dataSource = new DruidDataSource();
 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
 dataSource.setUrl("jdbc:mysql:///user_db");
 dataSource.setUsername("root");
 dataSource.setPassword("root");
 return dataSource;
 }
 //Create a JdbcTemplate object
 @Bean
 public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
 //Go to the ioc container and find the dataSource by type
 JdbcTemplate jdbcTemplate = new JdbcTemplate();
 //Inject dataSource
 jdbcTemplate.setDataSource(dataSource);
 return jdbcTemplate;
 }
 //Create transaction manager
 @Bean
 public DataSourceTransactionManager 
getDataSourceTransactionManager(DataSource dataSource) {
 DataSourceTransactionManager transactionManager = new 
DataSourceTransactionManager();
 transactionManager.setDataSource(dataSource);
 return transactionManager;
 } }

New features of spring 5 framework

1. The code of the whole spring 5 framework is based on Java 8, the runtime is compatible with JDK9, and many classes and parties are not recommended
Cannot delete from the code base
2. The Spring 5.0 framework comes with a general log encapsulation (1) the Log4jConfigListener has been removed from spring 5, and Log4j2 is officially recommended
(2) Spring 5 framework integration Log4j2
The first step is to introduce the jar package
Step 2: create log4j2.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!--Log level and prioritization: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > 
ALL -->
<!--Configuration hinder status Used to set log4j2 The internal information output can not be set,
When set to trace When, you can see log4j2 Various internal detailed outputs--> <configuration status="INFO">
 <!--Define all first appender-->
 <appenders>
 <!--Output log information to console-->
 <console name="Console" target="SYSTEM_OUT">
 <!--Controls the format of log output-->
 <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-
5level %logger{36} - %msg%n"/>
 </console>
 </appenders>
 <!--Then define logger,Only definition logger And introduced appender,appender Will take effect-->
 <!--root: Used to specify the root log of the project, if not specified separately Logger,Will be used root As
 Default log output-->
 <loggers>
 <root level="info">
 <appender-ref ref="Console"/>
 </root>
 </loggers>
</configuration>

3. The spring 5 framework core container supports the @ Nullable annotation
(1) The @ Nullable annotation can be used on methods, properties and parameters, indicating that the method return can be null and the property value can be null
If it is blank, the parameter value can be blank
(2) The annotation is used on the method, and the return value of the method can be null
(3) Annotations are used in method parameters, which can be empty
(4) Annotations are used on attributes. Attribute values can be empty
4. The spring 5 core container supports the functional style GenericApplicationContext

//Create objects in functional style and hand them over to spring for management
@Test
public void testGenericApplicationContext() {
 //1 create GenericApplicationContext object
 GenericApplicationContext context = new GenericApplicationContext();
 //2. Call the method object registration of context
 context.refresh();
 context.registerBean("user1",User.class,() -> new User());
 //3 get the object registered in spring
 // User user = (User)context.getBean("com.atguigu.spring5.test.User");
 User user = (User)context.getBean("user1");
 System.out.println(user);
}

5. Spring 5 supports the integration of JUnit 5
(1) Integrate JUnit 4
The first step is to introduce Spring related test dependencies
The second step is to create a test class and complete it with annotations

@RunWith(SpringJUnit4ClassRunner.class) //Unit test framework
@ContextConfiguration("classpath:bean1.xml") //Load profile
public class JTest4 {
 @Autowired
 private UserService userService;
 @Test
 public void test1() {
 userService.accountMoney();
 } }

(2) Spring 5 integrates JUnit 5
The first step is to introduce the jar package of JUnit 5
The second step is to create a test class and complete it with annotations

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {
 @Autowired
 private UserService userService;
 @Test
 public void test1() {
 userService.accountMoney();
 } }

(3) Use a composite annotation instead of the above two annotations to complete the integration

@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JTest5 {
 @Autowired
 private UserService userService;
 @Test
 public void test1() {
 userService.accountMoney();
 } }

New features of spring 5 framework (Webflux)

1. Introduction to spring Webflux

(1) Spring 5 adds a new module for web development. The function is similar to spring MVC. Webflux uses
At present, a framework for comparing process responsive programming appears.
(2) Using traditional web frameworks, such as spring MVC, which are based on Servlet containers, Webflux is an asynchronous non blocking
Plug framework, asynchronous non blocking framework is supported after servlet 3.1, and the core is the implementation of relevant API s based on Reactor
of
(3) Explain what asynchronous non blocking is

  • Asynchronous and synchronous
  • Non blocking and blocking

The above is for different objects

Asynchronous and synchronous are for the caller. If the caller sends a request and waits for the other party's response before doing other things, it is synchronous. If he does other things without waiting for the other party's response after sending the request, it is asynchronous blocking and non blocking. For the callee, the callee gives feedback after receiving the request and completing the request task is blocking, Giving feedback immediately after receiving a request and then doing something is non blocking
(4) Webflux features:
First, non blocking: under limited resources, improve system throughput and scalability, and realize responsive programming based on Reactor
Second, functional programming: the spring 5 framework is based on Java 8, and Webflux uses Java 8 functional programming to route requests
(5) Compare spring MVC
The first two frameworks can be annotated and run in containers such as Tomet
Second, spring MVC adopts imperative programming and Webflux adopts asynchronous response programming

2. Responsive programming (Java implementation)

(1) What is responsive programming
Responsive programming is a programming paradigm for data flow and change propagation. This means that it can be very convenient in the programming language
The static or dynamic data flow can be expressed, and the relevant calculation model will automatically propagate the changed values through the data flow.
A spreadsheet program is an example of responsive programming. Cells can contain literal values or public values like "= B1+C1"
Formula, and the value of the cell containing the formula will change according to the value of other cells.
(2) Java 8 and earlier

  • The provided Observer mode has two classes: Observer and Observable
public class ObserverDemo extends Observable {
 public static void main(String[] args) {
 ObserverDemo observer = new ObserverDemo();
 //Add observer
 observer.addObserver((o,arg)->{
 System.out.println("undergo changes");
 });
 observer.addObserver((o,arg)->{
 System.out.println("Manually notified by the observer, ready to change");
 });
 observer.setChanged(); //Data change
 observer.notifyObservers(); //notice
 } }

3. Responsive programming (implemented by Reactor)

(1) In Reactive programming operations, Reactor is a framework that meets the Reactive specification
(2) Reactor has two core classes, Mono and Flux, which implement the interface Publisher and provide rich operations
Symbol. The Flux object implements the publisher and returns N elements; Mono implements the publisher and returns 0 or 1 elements
(3) Flux and Mono are both publishers of data flow. Using flux and Mono, three data signals can be sent:
Element value, error signal, completion signal, error signal and completion signal all represent termination signal, and termination signal is used to tell
When the subscriber data stream ends, the error signal terminates the data stream and transmits the error message to the subscriber
(4) Code demonstration Flux and Mono
Step 1: introduce dependency

<dependency>
 <groupId>io.projectreactor</groupId>
 <artifactId>reactor-core</artifactId>
 <version>3.1.5.RELEASE</version>
</dependency>

Step 2 programming code

public static void main(String[] args) {
 //just method direct declaration
 Flux.just(1,2,3,4);
 Mono.just(1);
 //Other methods
 Integer[] array = {1,2,3,4};
 Flux.fromArray(array);
 
 List<Integer> list = Arrays.asList(array);
 Flux.fromIterable(list);
 Stream<Integer> stream = list.stream();
 Flux.fromStream(stream);
}

(5) Three signal characteristics

  • Both error signal and completion signal are termination signals and cannot coexist
  • If no element value is sent, but an error or completion signal is sent directly, it indicates an empty data stream
  • If there is no error signal and no completion signal, it indicates an infinite data stream
    (6) Calling just or other methods only declares the data flow. The data flow is not sent out and will be triggered only after subscription
    Send a data stream and nothing will happen without subscribing
    (7) Operator
  • The data stream is operated one after another to become an operator, such as a factory pipeline
    The first map element is mapped to a new element
    The second flatMap element maps to a stream
    ⚫ Convert each element into a stream, and merge multiple streams after conversion into a large stream

4. Spring Webflux execution process and core API s

Spring Webflux is based on Reactor. The default container is netty. Netty is a high-performance NIO framework, asynchronous and non blocking
Plug frame
(1)Netty

  • BIO
    NIO
    (2) The execution process of spring Webflux is similar to that of spring MVC
  • The spring Webflux core controller DispatchHandler implements the interface WebHandler
  • Interface WebHandler has a method
    (3) DispatcherHandler in spring Webflux is responsible for processing requests
  • HandlerMapping: the processing method of the request query
  • HandlerAdapter: really responsible for request processing
  • HandlerResultHandler: response result processing
    (4) Spring Webflux implements functional programming with two interfaces: RouterFunction (routing processing)
    And HandlerFunction

5. Spring Webflux (annotation based programming model)

Spring Webflux can be implemented in two ways: annotated programming model and functional programming model
The annotation programming model is similar to that used by spring MVC before. You only need to configure the relevant dependencies into the project,
SpringBoot automatically configures the relevant running containers. By default, the Netty server is used
The first step is to create a SpringBoot project and introduce Webflux dependencies
Step 2 configure the startup port number
Step 3: create packages and related classes
⚫ Entity class
⚫ Method for creating interface definition operation

//User operation interface
public interface UserService {
 //Query user by id
 Mono<User> getUserById(int id);
 //Query all users
 Flux<User> getAllUser();
 //Add user
 Mono<Void> saveUserInfo(Mono<User> user);
}

⚫ Interface implementation class

public class UserServiceImpl implements UserService {
 //Create a map collection to store data
 private final Map<Integer,User> users = new HashMap<>();
 public UserServiceImpl() {
 this.users.put(1,new User("lucy","nan",20));
 this.users.put(2,new User("mary","nv",30));
 this.users.put(3,new User("jack","nv",50));
 }
 //Query by id
 @Override
 public Mono<User> getUserById(int id) {
 return Mono.justOrEmpty(this.users.get(id));
 }
 //Query multiple users
 @Override
 public Flux<User> getAllUser() {
 return Flux.fromIterable(this.users.values());
 }
 //Add user
 @Override
 public Mono<Void> saveUserInfo(Mono<User> userMono) {
 return userMono.doOnNext(person -> {
 //Put values into the map set
 int id = users.size()+1;
 users.put(id,person);
 }).thenEmpty(Mono.empty());
 } }⚫ establish controller
@RestController
public class UserController {
 //Inject service
 @Autowired
 private UserService userService;
 //id query
 @GetMapping("/user/{id}")
 public Mono<User> geetUserId(@PathVariable int id) {
 return userService.getUserById(id);
 }
 //Query all
 @GetMapping("/user")
 public Flux<User> getUsers() {
 return userService.getAllUser();
 }
 //add to
 @PostMapping("/saveuser")
 public Mono<Void> saveUser(@RequestBody User user) {
 Mono<User> userMono = Mono.just(user);
 return userService.saveUserInfo(userMono);
 } }

⚫ explain
Spring MVC is implemented in the way of synchronous blocking, which is based on spring MVC + servlet + Tomcat
Implemented in spring Webflux, asynchronous and non blocking mode, based on spring Webflux + reactor + netty

6. Spring Webflux (based on functional programming model)

(1) When operating with the functional programming model, you need to initialize the server yourself
(2) Based on the functional programming model, there are two core interfaces: RouterFunction
To the corresponding handler and HandlerFunction. The core task defines two functions
And start the required server.
(3) Spring Webflux requests and responses are no longer ServletRequest and ServletResponse, but
ServerRequest and ServerResponse
The first step is to copy the annotated programming model project and retain the entity and service contents
Step 2: create a Handler (specific implementation method)

public class UserHandler {
 private final UserService userService;
 public UserHandler(UserService userService) {
 this.userService = userService;
 }
 //Query by id
 public Mono<ServerResponse> getUserById(ServerRequest request) {
 //Get id value
 int userId = Integer.valueOf(request.pathVariable("id"));
 //Null value processing
 Mono<ServerResponse> notFound = ServerResponse.notFound().build();
 //Call the service method to get the data
 Mono<User> userMono = this.userService.getUserById(userId);
 //Convert userMono to return
 //Using the Reactor operator flatMap
 return 
 userMono
 .flatMap(person -> 
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
 .body(fromObject(person)))
 .switchIfEmpty(notFound);
 }
 //Query all
 public Mono<ServerResponse> getAllUsers() {
 //Call the service to get the result
 Flux<User> users = this.userService.getAllUser();
 return 
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users,User.cl
ass);
 }
 //add to
 public Mono<ServerResponse> saveUser(ServerRequest request) {
 //Get user object
 Mono<User> userMono = request.bodyToMono(User.class);
 return 
ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
 } }

Step 3 initialize the server and write the Router
⚫ Method of creating route

//1 create a Router route
public RouterFunction<ServerResponse> routingFunction() {
 //Create a handler object
 UserService userService = new UserServiceImpl();
 UserHandler handler = new UserHandler(userService);
 //Set route
 return RouterFunctions.route(
 
GET("/users/{id}").and(accept(APPLICATION_JSON)),handler::getUserById)
 .andRoute(GET("/users").and(accept(APPLICATION_JSON)),handler::get
AllUsers);
}

⚫ Create server complete adaptation

//2. Create the server to complete the adaptation
public void createReactorServer() {
 //Routing and handler adaptation
 RouterFunction<ServerResponse> route = routingFunction();
 HttpHandler httpHandler = toHttpHandler(route);
 ReactorHttpHandlerAdapter adapter = new 
ReactorHttpHandlerAdapter(httpHandler);
 //Create server
 HttpServer httpServer = HttpServer.create();
 httpServer.handle(adapter).bindNow();
}

⚫ Final call

public static void main(String[] args) throws Exception{
 Server server = new Server();
 server.createReactorServer();
 System.out.println("enter to exit");
 System.in.read();
}

(4) Using WebClient call

public class Client {
 public static void main(String[] args) {
 //Call server address
 WebClient webClient = WebClient.create("http://127.0.0.1:5794");
 //Query by id
 String id = "1";
 User userresult = webClient.get().uri("/users/{id}", id)
 .accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(User
.class)
 .block();
 System.out.println(userresult.getName());
 //Query all
 Flux<User> results = webClient.get().uri("/users")
 .accept(MediaType.APPLICATION_JSON).retrieve().bodyToFlux(User
.class);
 results.map(stu -> stu.getName())
 .buffer().doOnNext(System.out::println).blockFirst();
 } }

Course summary

1. Spring framework overview

(1) The lightweight open source Java EE framework consists of two core components: IOC and AOP in order to solve enterprise complexity
(2) Spring version 5.2.6

2. IOC container

(1) IOC underlying principle (factory, reflection, etc.)
(2) IOC interface (BeanFactory) (3) IOC operation Bean Management (xml based) (4) IOC operation Bean Management (annotation based)

3,Aop

(1) AOP underlying principle: dynamic agent, with interface (JDK dynamic agent) and no interface (CGLIB dynamic agent)
(2) Terms: entry point, enhancement (notification), aspect
(3) Implementation of AOP operation based on AspectJ

4,JdbcTemplate

(1) Using JdbcTemplate to implement database curd operation
(2) Using JdbcTemplate to realize database batch operation

5. Transaction management

(1) Transaction concept
(2) Important concepts (communication behavior and isolation level)
(3) Implementing declarative transaction management based on annotations
(4) Fully annotated implementation of declarative transaction management

6. What's new in spring 5

(1) Integrated logging framework
(2) @ Nullable annotation
(3) Functional registration object
(4) Integrate JUnit 5 unit test framework
(5) Using spring Webflux

Topics: Java Spring