Today’s sharing started, please give us more advice ~

Overview of the Spring5 framework

Spring is a lightweight open source JavaEE framework

Spring solves the complexity of enterprise application development

Spring has two core parts: IOC and Aop

(1) IOC: Inversion of control, leaving the object creation process to Spring for management;

(2) Aop: section-oriented, without modifying the source code for functional enhancement;

4. Spring features

(1) Convenient decoupling and simplified development

(2) Aop programming support

(3) Convenient program testing

(4) Convenient integration with other frameworks

(5) Facilitate transaction operations

(6) Reduce the difficulty of API development

5. Based on The Spring version 5.x

Two, Spring5 introduction case

1. Download Spring5

Use Spring’s latest stable release 5.2.6

2. Open idea and create a common Java project

3. Import the relevant jar packages of Spring5

4. Create a normal class. Create a normal method in this class

5. Create a Spring configuration file and configure the created objects in the configuration file

The Spring configuration file uses XML format

6. Write test code

Third, the IOC

1. What is IOC

(1) Inversion of control, transferring the object creation and call between objects to Spring for management;

(2) The purpose of using IOC: to reduce the coupling degree;

(3) To do the introductory case is IOC implementation;

2. Underlying principles of IOC

XML parsing, factory schema, reflection;

3. Explain the underlying principles of IOC by drawing pictures

  1. IOC (BeanFactory Interface)

1. IOC thought is based on IOC container, and the bottom of IOC container is object factory.

2. Spring provides two ways to implement IOC containers :(two interfaces)

(1) BeanFactory: The basic implementation of IOC container, which is an internal interface of Spring and not available for developers to use;

Objects are not created when the configuration file is loaded. Objects are created when the object is retrieved.

ApplicationContext: a subinterface of the BeanFactory interface that provides more powerful functions and is generally used by developers;

The configuration file object is created when the configuration file is loaded.

The ApplicationContext interface has implementation classes

  1. IOC operation Bean Management (concept)

1. What is Bean management

(1) Bean management refers to two operations

(2) Spring creates objects

(3) Spirng injection attribute

There are two ways to manage Bean operations

(1) Implementation based on XML configuration file

(2) Based on annotations

  1. IOC operation Bean Management (XML-based)

1. Create objects based on XML

(1) In the Spring configuration file, use the bean tag, tag to add corresponding attributes, you can achieve object creation;

(2) There are many attributes in the bean tag.

Id attribute: Unique identifier

Class attribute: classpath (package classpath)

(3) When creating an object, the default is to execute the no-argument constructor to complete the object creation;

2. Inject attributes based on XML

DI: Dependency injection, which is to inject properties

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

Create a class that defines attributes and corresponding set methods

(2) Configure object creation and property injection in the Spring configuration file

4. The second injection method: use a parameterized construct for injection

(1) Create class, define attribute, create attribute pair should parameter constructor

(2) Configure in the Spring configuration file

5. P namespace injection (understanding)

(1) Using P namespace injection can simplify xmL-based configuration

The first step is to add the p namespace to the configuration file

The second step is property injection, which takes place inside the bean label

  1. IOC operation Bean management (XML injection of other types of attributes)

1. Literals

(1) Null value

(2) Attribute values contain special symbols

Inject properties – external beans

(1) Create two classes: Service and DAO

(2) Call dao methods in service

(3) Configure in the Spring configuration file

Inject properties – inner beans

(1) One-to-many relationship: departments and employees

A department has multiple employees. One employee belongs to a department. A department is one, and there are many employees

(2) One-to-many relationship is represented between entity classes, and the employee represents the department to which he belongs, which is represented by object type attribute

(3) Configure in the Spring configuration file

4. Inject properties – Cascade assignments

(1) The first way

(2) The second way

  1. IOC operation Bean Management (XML injection collection attributes)

1. Inject array type attributes

Inject the List collection type attribute

3. Inject Map collection type attributes

(1) Create classes, define array, list, map and set type attributes, and generate corresponding set methods

(2) Configure in the Spring configuration file

4. Set the object type value in the collection

Extract the collection injection part

(1) Introduce the namespace util in the Spring configuration file

(2) Use util tag to complete list collection injection extraction

  1. IOC Operation Bean Management (FactoryBean)

Spring has two types of beans: normal beans and factory beans.

2. Plain beans: Define the bean type as the return type in the configuration file

Factory beans: Define bean types in configuration files that are different from return types

The first step is to create a class that acts as a FactoryBean and implements the interface FactoryBean

The second step implements the method in the interface, defining the returned bean type in the implemented method

  1. IOC operation Bean Management (Bean scope)

1. In Spring, set whether to create a single or multi-instance bean instance

2. In Spring, beans are singleton objects by default

3. How to set single-instance or multi-instance

(1) In the Spring configuration file bean tag there is a property (scope) for setting single or multiple instances

(2) Scope attribute value

The first value, the default value, singleton, represents a singleton

The second value, prototype, indicates a multi-instance object

(3) Difference between Singleton and Prototype

First singleton instance, prototype multi-instance

When the second scope value is singleton, the singleton object is created when the Spring configuration file is loaded

When setting scope to prototype, instead of creating an object when loading the Spring configuration file, create a multi-instance object when calling the getBean method.

  1. IOC operation Bean Management (Bean life cycle)

1. Life cycle

(1) Process from object creation to object destruction

2. Bean lifecycle

(1) Create a bean instance from a constructor (no arguments)

(2) Set values for bean properties and references to other beans (call set method)

(3) Call bean initialization methods (methods that need configuration initialization)

(4) Bean ready to use (object acquired)

(5) When the container is closed, call the bean’s destruction method (the method that requires configuration destruction).

Demonstrate the bean life cycle

4. Bean post-processor, bean life cycle has seven steps

(1) Create a bean instance from a constructor (no arguments)

(2) Set values for bean properties and references to other beans (call set method)

(3) Pass bean instances to bean preprocessor methods

postProcessBeforeInitialization

(4) Call bean initialization methods (methods that need configuration initialization)

(5) the rear pass bean instance bean postProcessAfterInitialization processor

(6) The bean is ready to use.

(7) When the container is closed, call the bean’s destruction method (which requires configuration destruction).

5. Demonstrate the effect of adding a rear processor

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

  1. IOC operation Bean Management (XML autowiring)

1, what is automatic assembly

(1) According to the specified assembly rule (attribute name or attribute type), Spring will automatically inject the matched attribute value

2. Demonstrate the automatic assembly process

(1) Automatic injection according to the attribute name

(2) Automatic injection according to the attribute type

  1. IOC operation Bean Management (external properties file)

1. Directly configure the database information

(1) Configure a druid connection pool

(2) Introduce druid connection pool dependency JAR package

2. Introduce an external properties file to configure the database connection pool

(1) Create external properties file, properties format file, write database information

(2) Introduce the external properties property file into the Spring configuration file

Introduce the context namespace

Use tags to introduce external properties files in the Spring configuration file

  1. IOC operation Bean Management (annotation-based)

1. What are annotations

(1) Annotations are code special tags, format: @ annotation name (attribute name = attribute value, attribute name = attribute value…)

(2) Use annotations, which apply to classes, methods, and properties

(3) Use annotations to simplify XML configuration

Spring provides annotations for creating objects in Bean management

(1) @ Component

(2) @ Service

(3) @ Controller

(4) @ the Repository

The above four annotations are identical and can be used to create bean instances

3. Object creation based on annotations

The first step is to introduce dependencies

Step 2 Enable component scanning

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

4. Enable component scanning details

5. Implement attribute injection based on annotation

(1) @autoWired: automatic assembly according to the attribute type

The first step is to create the Service and DAO objects. Add create object annotations to the Service and DAO classes

The second step is to inject the DAO object into the Service, add dao type attributes to the Service class, and use annotations on the attributes

(2) @qualifier: inject according to name

The use of the @Qualifier annotation is used in conjunction with @autoWired above

(3) @resource: can be injected by type, can be injected by name

(4) @value: Inject common type attributes

@Value(value = “abc”)

private String name;

6. Fully annotated development (

1) Create a configuration class instead of an XML configuration file

(2) Write test classes

Four, AOP

1. What is AOP

(1) For section programming (aspect), the use of AOP can be isolated to each part of the business logic, so that

The coupling degree between the various parts of the business logic is reduced, which improves the reusability of the program and the efficiency of development.

(2) Popular description: without modifying the source code, add new features in the trunk function

(3) Use login examples to illustrate AOP

  1. AOP (Underlying principles)

AOP uses dynamic proxies underneath

(1) There are two cases of dynamic proxy

The first case with interfaces uses the JDK dynamic proxy

Create an interface to implement a class proxy object that enhances the class’s methods

In the second case, where there is no interface, the CGLIB dynamic proxy is used

Create a subclass’s proxy object to enhance the class’s methods

  1. AOP (JDK Dynamic Proxy)

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

(1) Call newProxyInstance

The method takes three arguments:

The first argument, the class loader

The second argument is the class in which the enhanced method resides. This class implements an interface that supports multiple interfaces

The third argument implements the interface InvocationHandler, creates the proxy object, and writes the enhanced part

2. Write JDK dynamic proxy code

(1) Create interfaces and define methods

(2) Create interface implementation classes and implement methods

(3) Use Proxy class to create interface Proxy object

  1. AOP (terminology)

  2. AOP operations (preparation)

1. The Spring framework generally implements AOP operations based on AspectJ

(1) AspectJ is not part of Spring. It is an independent AOP framework. AspectJ and Spirng framework are generally used together for AOP operations

2. Implement AOP operations based on AspectJ

(1) Implementation based on XML configuration file

(2) Annotation based implementation (use)

3. Introduce AOP-related dependencies into your project

Pointcut expressions

(1) Pointcut expressions are used to know which methods in which classes are enhanced

(2) Grammar structure:

Execution ([permission modifier] [return type] [class full path] method name)

Example 1:

Add is enhanced in the com.atguigu.dao.bookdao class

Execution (* com. Atguigu. Dao. BookDao. Add (…). )

Example 2:

Enhance all methods in the com.atguigu.dao.bookdao class

Execution (* com. Atguigu. Dao. BookDao. * (…). )

Example 3:

Dao package for all classes, all methods in the class to enhance

execution(* com.atguigu.dao.. (…). )

  1. AOP operations (AspectJ annotations)

1. Create a class and define methods in it

2. Create enhancement class (write enhancement logic)

(1) In the enhanced class, create methods that represent different notification types

3. Configure notification

(1) In the Spring configuration file, enable annotation scanning

(2) Create User and UserProxy objects using annotations

(3) Add the @aspect annotation to the enhanced class

(4) Enable generation of proxy objects in the Spring configuration file

4. Configure different types of notification

(1) In the enhanced class, add the notification type annotation above the notification method, using the pointcut expression configuration

5. Same pointcut extraction

6, there are multiple enhancement classes to enhance the same method, set the priority of the enhancement class

(1) Add the annotation @ORDER (numeric type value) above the enhanced class. The smaller the numeric type value, the higher the priority

7. Develop entirely with annotations (

1) Create a configuration class without creating an XML configuration file

  1. AOP operations (AspectJ configuration files)

1. Create two classes, the enhanced class and the enhanced class, and create methods

2. Create two class objects in the Spring configuration file

Configure the pointcut in the Spring configuration file

JdbcTemplate(concept and preparation)

What is a JdbcTemplate

(1) Spring framework for JDBC encapsulation, the use of JdbcTemplate convenient implementation of database operations

2. Preparation

(1) Introduce relevant JAR packages

(2) Configure the database connection pool in the Spring profile

Insert JdbcTemplate into DataSource

(4) Create service class, create DAO class, inject jdbcTemplate object into DAO

The configuration file

Service

Dao

  1. JdbcTemplate operation database (add)

1. Create an entity class for the database

2. Write services and DAOs

(1) Add the database in DAO

Update (JdbcTemplate)

There are two parameters

⚫ First parameter: SQL statement

⚫ Second parameter: variable parameter, set the SQL statement value

3. Test classes

  1. JdbcTemplate operates on the database (modify and delete)

1, modify,

2, remove,

  1. JdbcTemplate operates on the database (the query returns a value)

1, query the number of records in the table, return a certain value

2. Use JdbcTemplate to implement the query to return a value code

There are two parameters

⚫ First parameter: SQL statement

⚫ Second argument: return type Class

  1. JdbcTemplate operation database (query return object)

1. Scenario: Query book details

2, JdbcTemplate implementation query return object

There are three parameters ⚫ The first parameter: SQL statement

⚫ The second argument: RowMapper is the interface for returning different types of data, using the implementation class in this interface to complete the data encapsulation

⚫ Third parameter: SQL statement value

  1. JdbcTemplate operation database (query return collection)

1, scenario: query book list page…

2. Call the JdbcTemplate method to implement the query return collection

There are three parameters

⚫ First parameter: SQL statement

⚫ The second argument: RowMapper is the interface for returning different types of data, using the implementation class in this interface to complete the data encapsulation

⚫ Third parameter: SQL statement value

  1. JdbcTemplate operation database (batch operation)

1. Batch operation: Operate multiple records in the table

2. JdbcTemplate implements batch add operation

There are two parameters

⚫ First parameter: SQL statement

⚫ Second parameter: List collection, add multiple records of data

3. JdbcTemplate implements batch modification operations

4, JdbcTemplate to achieve batch delete operation

Transaction operation

1. What business

(1) Transactions are the most basic unit of database operations. Logically, a group of operations will either succeed, or if one fails, all operations will fail

(2) Typical scenario: bank transfer

Lucy transferred 100 yuan to Mary

Lucy is 100 less, Mary is 100 more

2. Four properties of transaction (ACID)

(1) atomicity

(2) Consistency

(3) Isolation

(4) Persistence

  1. Transaction operation (setting up transaction operation environment)

1, create a database table, add records

2. Create service, build DAO, and complete object creation and injection relationship

(1) Service inject DAO, JdbcTemplate, JdbcTemplate

Create two methods in DAO: more money and less money methods, and create a method in Service (transfer method)

4, the code, if the normal execution of no problem, but if there is an exception in the code execution process, there is a problem

(1) How to solve the above problems?

* Use transactions for resolution

(2) Transaction operation process

  1. Transaction Operations (Introduction to Spring Transaction Management)

1. Transactions are added to the Service layer (business logic layer) in the JavaEE three-layer structure.

2. Perform transaction management operations in Spring

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

Declarative transaction management

(1) Based on annotations (use)

(2) Based on XML configuration files

4. Declarative transaction management in Spring, using AOP principle at the bottom

5. Spring Transaction Management API

(1) Provide an interface representing the transaction manager, which provides different implementation classes for different frameworks

  1. Transaction operations (annotated declarative transaction management)

1. Configure the transaction manager in the Spring configuration file

2. In the Spring configuration file, turn on transaction annotations

(2) Turn on transaction annotations

Add transaction annotations above the service class (or above the methods in the Service class)

(1) @Transactional, this annotation is added to classes or methods

(2) If you add this annotation to a class, all methods in the class add transactions

(3) Add a transaction to the method if the annotation is added to the method

  1. Transaction operations (declarative transaction management parameter configuration)

Add the @Transactional annotation to the Service class to configure Transactional parameters

Propagation: Transaction propagation behavior

(1) The multi-transaction method is called directly. How is the transaction managed in this process

Ioslation: transaction isolation level

(1) Transactions have the characteristics of isolation, and there is no impact between multiple transaction operations. Not considering isolation creates many problems

(2) There are three reading problems: dirty reading, unrepeatable reading, virtual (phantom) reading

(3) Dirty read: one uncommitted transaction reads data from another uncommitted transaction

(4) Unrepeatable read: one uncommitted transaction reads the modified data of another committed transaction

(5) Virtual read: an uncommitted transaction reads data to another committed transaction

(6) Solution: Set the transaction isolation level to solve the read problem

(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 setting time is calculated in seconds

5. ReadOnly: Indicates whether it is read-only

(1) Read: query operation; write: add, modify and delete operation

(2) readOnly Default value false: indicates that you can query, add, modify, or delete information

(3) Set the value of readOnly to true

6. RollbackFor: rolls back

(1) Set which exceptions occur for transaction rollback

7. NoRollbackFor: does not roll back

(1) Set which exceptions do not carry out transaction rollback

  1. Transactional operations (XML declarative transaction management)

1. Configure in the Spring configuration file

The first step is to configure the transaction manager

Step 2 Configure notification

The third step configures the pointcut and aspect

  1. Transaction operations (fully annotated declarative transaction management)

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

New features in the Spring5 framework

1. The code of the entire Spring5 framework is based on Java8 and is compatible with JDK9 at runtime. Many deprecated classes and methods are removed from the code base

2. The Spring 5.0 framework comes with generic logging encapsulation

(1) Log4jConfigListener has been removed from Spring5, and Log4j2 is officially recommended

(2) The Spring5 framework integrates Log4j2

The first step is to introduce the JAR package

Step 2 Create the log4j2.xml configuration file

3. The Spring5 framework core container supports the @nullable annotation

(1) @nullable can be used for methods, properties, and parameters to indicate that method returns can be null, property values can be null, and parameter values can be null

(2) Annotations are used on methods that can return a null value

(3) Annotations are used in method parameters, which can be empty

(4) Annotations are used on attributes, and attribute values can be null

4, Spring5 GenericApplicationContext core container support functional style

5. Spring5 supports integration with JUnit5

(1) Integrate JUnit4

The first step is to introduce Spring dependencies for testing dependencies

The second step is to create the test class, using annotations

(2) Spring5 integrates JUnit5

The first step is to import the JUnit5 JAR package

The second step is to create the test class, using annotations

7. New features of Spring5 framework (Webflux)

1. Introduction to SpringWebflux

(1) Spring5 adds a new module for Web development, similar in function to SpringMVC, Webflux uses a current framework that compares process responsive programming.

(2) Use traditional Web frameworks, such as SpringMVC, which are based on Servlet containers. Webflux is an asynchronous non-blocking framework, which was not supported until after Servlet3.1. The core is implemented based on Reactor API.

(3) Explain what is asynchronous non-blocking

Asynchrony and synchronization

Non-blocking and blocking

The above are for different objects

Asynchrony and synchronization are for callers. The caller sends a request and waits for a response before doing something else. The caller sends a request and waits for a response before doing something else.

Blocking and non-blocking are for the called person. The called person gets the request and then gives feedback after the requested task is blocked, and the called person gives feedback immediately after the request and then does the task is non-blocking.

(4) Characteristics of Webflux:

First, non-blocking: Improve system throughput and scalability under limited resources, and implement responsive programming based on Reactor

Second, functional programming: the Spring5 framework is based on java8, and Webflux uses java8 functional programming to implement routing requests

(5) Compare SpringMVC

The first two frameworks can use annotations and both run in containers such as Tomet

The second SpringMVC adopts imperative programming and Webflux adopts asynchronous responsive 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 static or dynamic data flows can be easily expressed in a programming language, and the associated computational model automatically propagates the changing values through the data flows. A spreadsheet program is an example of reactive programming. Cells can contain literals or formulas like “=B1+C1”, and the value of the cell containing the formula changes depending on the value of the other cells.

(2) Java8 and earlier versions

Provides two Observer mode classes, Observer and Observable

3. Responsive programming (Reactor implementation)

(1) In the Reactive programming operation, Reactor meets the Reactive specification framework

(2) Reactor has two core classes, Mono and Flux, which implement the interface Publisher and provide rich operators. The Flux object implements the publisher and returns N elements; Mono implementation publisher, returns 0 or 1 element

(3) Flux and Mono are both publishers of data streams. Using Flux and Mono, they can send three data signals: Element values, error signals, completion signals, error signals, and completion signals all represent termination signals, which are used to tell the subscriber that the data stream has ended, and error signals which terminate the data stream and pass error messages to the subscriber

(4) Code to demonstrate Flux and Mono

The first step is to introduce dependencies

Step 2 Programming code

5) Three signal characteristics

Error signals and completion signals are both termination signals and cannot coexist

If no element value is sent, an error or completion signal is sent directly, indicating an empty data stream

If there is no error signal, no completion signal, it is an infinite data stream

(6) A call to just or any other method declares a data stream, and the data stream is not emitted. The data stream is triggered only after the subscription, and nothing happens without the subscription

(7) Operator

Operations on a data stream are called operators, such as a factory pipeline

The first map element is mapped to the new element

The second flatMap element is mapped to a flow

Each element is converted into a stream, and multiple streams are merged into a larger stream

4. SpringWebflux executes processes and core apis

SpringWebflux is based on Reactor and uses Netty as the default container. Netty is a high-performance NIO framework and an asynchronous non-blocking framework

(1) the Netty

BIO

NIO

(2) SpringWebflux execution process is similar to SpringMVC

SpringWebflux core controller DispatchHandler implements the interface WebHandler

The interface WebHandler has a method

(3) SpringWebflux DispatcherHandler is responsible for processing requests

HandlerMapping: Processing method of request query

HandlerAdapter: Actually handles request processing

HandlerResultHandler: Response result processing

(4) SpringWebflux implements functional programming with two interfaces: RouterFunction (routing processing) and HandlerFunction (handling function).

5. SpringWebflux (Annotation-based programming model)

SpringWebflux is implemented in two ways: an annotation programming model and a functional programming model

Using the annotation programming model approach, similar to the previous SpringMVC approach, you just configure the dependencies into the project,

SpringBoot automatically configures the associated running containers, using Netty servers by default

The first step is to create a SpringBoot project and introduce Webflux dependencies

Step 2 Configure the boot port number

Step 3 Create the package and related classes

⚫ entity class

⚫ Create an interface to define an operation

⚫ Interface implementation class

⚫ create controller

⚫ instructions

Synchronous blocking is implemented based on SpringMVC+Servlet+Tomcat SpringWebflux. Asynchronous non-blocking is implemented based on SpringWebflux+Reactor+Netty

6. SpringWebflux (Based on functional programming Model)

(1) When operating using the functional programming model, you need to initialize the server yourself

(2) Based on the functional programming model, there are two core interfaces: RouterFunction (which implements routing and forwards requests to corresponding handlers) and HandlerFunction (which processes requests and generates responses). The core task defines the implementation of the two functional interfaces and starts the required servers.

(3) SpringWebflux requests and rings should no longer be ServletRequest and ServletResponse, but rather

ServerRequest and ServerResponse

The first step is to make a copy of the annotation programming model project, keeping the Entity and Service content

Step 2 Create Handler (implementation method)

Step 3 Initialize the server and write the Router

⚫ Method of creating a route

⚫ Creating a server is complete

⚫ Final call

(4) Use WebClient to call

Today’s share has ended, please forgive and give advice!