Spring modules

Spring is a lightweight Inversion of Control (IoC) and AOP oriented open source framework for containers.

Spring core container

The container is the core part of the Spring framework that manages the creation, configuration, and management of beans in Spring applications. In this module, the Spring Bean factory is included, which provides DI functionality for Spring. Based on the bean factory, we will also find multiple implementations of Spring application contexts, each of which provides a different way to configure Spring. In addition to the bean factory and application context, the module also provides many enterprise services, such as E-mail, JNDI access, EJB integration, and scheduling. All Spring modules are built on top of the core container.

Spring’s AOP module

In AOP modules, Spring provides rich support for section-oriented programming. This module is the basis for developing facets in Spring applications. Like DI, AOP can help decouple application objects. With AOP, you can decouple system-wide concerns, such as transactions and security, from the objects to which they apply.

Data access and integration

Writing code using JDBC typically results in a lot of boilerplate code, such as obtaining database connections, creating statements, processing result sets, and finally closing database connections. Spring’s JDBC and DAO (Data Access Object) modules abstract away this boilerplate code, making our database code straightforward and avoiding problems caused by failure to shut down database resources. Many popular ORM frameworks are integrated, including Hibernate, Java Persister APIS, Java Data Objects, and iBATIS SQL Maps. Spring’s transaction management supports all ORM frameworks as well as JDBC.

Web and Remote Call MVC (Model-View-Controller)

The MVC pattern is a widely accepted approach to building Web applications, which helps users separate interface logic from application logic. Java has no shortage of MVC frameworks, and Apache’s Struts, JSF, WebWork, and Tapestry are among the most popular MVC frameworks available. While Spring can integrate with a variety of popular MVC frameworks, its Web and remote invocation modules come with a powerful MVC framework that helps promote loose coupling of applications at the Web layer. The module also provides a variety of remote invocation schemes for building interactions with other applications. Spring’s Remote Invocation integrates WITH Remote Method Invocation (RMI), Hessian, Burlap, JAX-WS, and also comes with HTTP Invoker, a Remote Invocation framework. Spring also provides good support for exposing and using REST apis.

Instrumentation

Spring’s Instrumentation module provides the ability to add agents to the JVM. Specifically, it provides an weaving proxy for Tomcat that can pass class files to Tomcat as if they were loaded by the class loader.

test

Given the importance of self-testing by developers, Spring provides test modules to focus on testing Spring applications. Through this module, you’ll find that Spring provides a series of mock object implementations for writing unit tests using JNDI, servlets, and portlets. For integration testing, this module provides support for loading and interacting with collections of beans in the Spring application context.

The Spring IOC container

Inversion of Control, or IoC, is a design principle used in object-oriented programming to reduce coupling between computer code. One of the most common is called Dependency Injection, or DI, and another is called Dependency Lookup. With inversion of control, when an object is created, it is passed a reference to the object on which it depends by an external entity that regulates all objects in the system. In other words, dependencies are injected into objects.

The IoC container has two main responsibilities:

  • Build management of business objects. In an IoC scenario, business objects don’t have to care about how the objects they depend on are built or acquired, but someone always has to do that. The IoC is responsible for separating the object’s build logic from the client object so that it does not contaminate the implementation of the business object.
  • Dependent binding between business objects. IoC injects bindings into the objects on which these objects depend by combining all business objects previously built and managed and identifiable dependencies among them, so as to ensure that each business object can be in a ready state when it is used.

Spring provides two container types:

  • The BeanFactory. Base type IoC container that provides complete IoC service support. If no specific initialization policy is specified, lazy-load is used by default. Initialization and dependency injection are performed only when the client object needs to access a managed object in the container. As a result, containers are relatively quick to start up and require limited resources. For scenarios with limited resources and less stringent functional requirements, BeanFactory is a suitable IoC container choice.
  • ApplicationContext. ApplicationContext is built on top of BeanFactory and is a relatively high-level container implementation. In addition to having all the support of BeanFactory, ApplicationContext also provides other high-level, Such as event publishing, international information support and so on. Objects managed by ApplicationContext are all initialized and bound by default after the container of that type is started. The ApplicationContext requires more system resources than the BeanFactory, and the container takes longer to start than the BeanFactory container because all initialization is done at startup. In scenarios where system resources are plentiful and more functionality is required, containers of type ApplicationContext are the appropriate choice.

ApplicationContext indirectly inherits from the BeanFactory, so it is an IoC container built on top of the BeanFactory

Spring comes with many types of application contexts

  • AnnotationConfigApplicationContext: from one or more configuration based on Java class loading Spring application context.
  • AnnotationConfigWebApplicationContext: from one or more configuration based on Java class loading Spring Web application context.
  • ClassPathXmlApplicationContext: from the classpath of one or more XML configuration file loaded context definition, define the application context file as a resource.
  • FileSystemXmlapplicationcontext: from the file system under one or more loading context defined in the XML configuration files.
  • XmlWebApplicationContext: Loads the context definition from one or more XML configuration files under the Web application.

IoC container operation phase

Spring’s IoC container can be divided into two phases, namely container startup and Bean instantiation, basically following a similar process

1. Container startup

When the container is started, Configuration MetaData is first loaded in some way. Except for direct code, in most cases, containers need to rely on beandefinitionReaders to parse and analyze loaded Configuration MetaData, and group the analyzed information into corresponding Beandefinitions. Finally, these BeanDefinitions, which hold the necessary bean definition information, are registered with the appropriate BeanDefinitionRegistry, and container startup is complete.

2. Bean instantiation phase

All bean definition information is registered with the BeanDefinitionRegistry as BeanDefinition. The second-phase activity is triggered when a requester explicitly requests an object through the container’s getBean method, or when the dependency container needs to implicitly invoke the getBean method. In this phase, the container first checks to see if the requested object has been initialized before. If not, the requested object is instantiated and its dependencies are injected based on the information provided by the registered BeanDefinition. If the object implements some callback interface, it is also assembled according to the callback interface requirements. When the object is assembled, the container immediately returns it to the requester for use.

The life cycle of the bean

In a Spring-based application, your application objects live in a Spring container. The Spring container is responsible for creating objects, assembling them, configuring them, and managing their entire life cycle, from living to dying (in this case, maybe new to Finalize ())

In traditional Java applications, the bean life cycle is simple. The bean is instantiated using the Java keyword new, and the bean can then be used. Once the bean is no longer in use, it is automatically garbage collected by Java.

A typical lifecycle process in which beans are loaded into the Spring application context

Before the bean is ready, the bean factory performs several startup steps.

1. Spring instantiates the bean;

2. Spring injects values and bean references into the bean’s corresponding properties;

3. If the bean implements the BeanNameAware interface, Spring passes the bean ID to the setbean-name () method;

4. If the bean implements the BeanFactoryAware interface, Spring calls the setBeanFactory() method, passing in the BeanFactory container instance;

5. If the bean implements the ApplicationContextAware interface, Spring calls the setApplicationContext() method, passing in a reference to the bean’s application context;

6. If the bean implements the BeanPostProcessor interface, the Spring will invoke them postProcessBeforeInitialization () method;

7. If the beans implement the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean declares an initialization method with init-method, that method is also called;

8. If the bean implements the BeanPostProcessor interface, Spring will call their post – ProcessAfterInitialization () method;

9. At this point, the beans are ready to be used by the application, and they will reside in the application context until the application context is destroyed;

10. If the bean implements the DisposableBean interface, Spring will call its destroy() interface method. Also, if the bean declares a destroy-method method, that method will be called.

The scope of the bean

By default, all beans in the Spring application context are created as singletons. That is, no matter how many times a given bean is injected into other beans, the same instance is injected each time.

Spring defines a variety of scopes, specified with the @scope annotation, on which beans can be created, including:

  • Singleton: Only one instance of the bean is created throughout the application.
  • Prototype: A new bean instance is created each time it is injected or retrieved through the Spring application context.
  • Session: In a Web application, one bean instance is created for each Session.
  • Request (Rquest) : In a Web application, a bean instance is created for each request

@scope also has a proxyMode property. This property solves the problem of injecting session – or request-scoped beans into singleton beans.

Faceted programming AOP

When using section-oriented programming, we still define common functionality in one place, but we can declaratively define how and where this functionality is applied without modifying the affected classes. Crosscutting concerns can be modularized into special classes called aspects. This has two benefits: first, each focus is now in one place, rather than scattered across multiple code sites; Second, the service module is more concise.

AOP terminology

Advice

The cutting side of the work is called notification. Spring facets can apply five types of notifications:

  • Before: call notification Before the target method is called;
  • After notification: the notification is called After the target method has completed, regardless of what the output of the method is.
  • Post-returning notification: notification is called After successful execution of the target method;
  • After-throwing: calls notifications After the target method throws an exception;
  • Around advice: Advice wraps the notified method, performing custom behavior before and after the notified method invocation

Join point

A join point is a point at which an aspect can be inserted during application execution. This point can be when a method is called, when an exception is thrown, or even when a field is modified. These points can be used by aspect code to plug into the normal flow of your application and add new behavior.

Poincut

The definition of the pointcut matches one or more join points that the advice is woven into. We usually specify these pointcuts using either explicit class and method names, or regular expressions that define matching class and method names.

Aspect

A section is a combination of notification and pointcut. Together, advice and pointcuts define the whole story of an aspect — what it is, when and where it does its job.

Introduction

Imports allow us to add new methods or attributes to existing classes. For example, we could create an Auditable notification class that records the state of the object when it was last modified. It’s simple, just a method, setLastModified(Date), and an instance variable to hold the state. This new method and instance variable can then be introduced into existing classes, giving them new behavior and state without having to modify them.

Weaving

Weaving is the process of applying a facet to a target object and creating a new proxy object. The section is woven into the target object at the specified join point. There are multiple points that can be woven into the life cycle of the target object:

  • Compile time: The aspect is woven in when the target class is compiled. This approach requires a special compiler. AspectJ’s weaving compiler weaves facets in this way.
  • Class loading time: The aspect is woven when the target class is loaded into the JVM. This approach requires special classloaders that enhance the bytecode of the target class before it is introduced into the application. AspectJ 5’s load-time Weaving (LTW) supports weaving into sections in this way. shipment
  • Run-time: Facets are woven in at some point during the application run. Typically, the AOP container dynamically creates a proxy object for the target object when weaving into the cut. Spring AOP is woven into the facets in this way.

Spring’s support for AOP

Creating pointcuts to define the join points woven into the aspects is a basic function of an AOP framework.

Spring provides four types of AOP support

  • Proxy-based classic Spring AOP;
  • Pure POJO section;
  • @AspectJ annotation-driven facets;
  • Injection AspectJ facets (available for Spring versions).

The first three are all variations of the implementation of Spring AOP, which is built on dynamic proxies, so Spring’s support for AOP is limited to method interception

Spring weaves the aspects into spring-managed beans at run time by wrapping them in a proxy class. The proxy class encapsulates the target class, intercepts the invocation of the notified method, and forwards the invocation to the actual target bean. When the proxy intercepts a method call, the aspect logic is performed before calling the target bean method.

The implementation mechanism of Spring AOP

Spring AOP is implemented by dynamic proxy mechanism and bytecode generation technology. And initial AspectJ adopt the compiler will crosscutting logic woven into the target object is different, the dynamic proxy mechanism and bytecode generation are at run time as target to generate a proxy object, and weave crosscutting logic to this proxy objects and eventually use is woven into the crosscutting logic proxy objects, rather than a true target object.

Spring AOP uses the CGLIB library’s dynamic bytecode enhancement support to extend AOP functionality when dynamic proxies are not available.

Because Spring is based on dynamic proxies, Spring only supports method join points. This is different from some other AOP frameworks, such as AspectJ and JBoss, which provide field and constructor access points in addition to method pointcuts. Spring lacks support for field join points to allow us to create fine-grained notifications, such as intercepting changes to object fields. And since it does not support constructor join points, we cannot apply notifications at bean creation time. But method interception meets most of the requirements. If you need join point interception capabilities beyond method interception, you can leverage aspects to complement Spring AOP’s capabilities.

A dynamic proxy

After JDK1.3, a mechanism called Dynamic Proxy was introduced. Using this mechanism, we can dynamically generate proxy objects for specified interfaces during system runtime. The realization of the dynamic Proxy mechanism is mainly composed of a class and an interface, or Java. Lang. Reflect. The Proxy class and Java. Lang. Reflect. InvocationHandler interface.

When the corresponding interface method is called on the Proxy object dynamically generated by Proxy, the corresponding InvocationHandler intercepts the corresponding method call and processes it accordingly. InvocationHandler is where we implement the crosscutting logic. It is the carrier of the crosscutting logic and acts as Advice. Therefore, in implementing AOP using dynamic proxy mechanisms, we can refine the program structure based on InvocationHandler and differentiate the program structure corresponding to different types of Advice. The dynamic proxy mechanism can only be used for classes that implement corresponding interfaces. If a class does not implement any Interface, the dynamic proxy mechanism cannot be used to generate corresponding dynamic proxy objects for it. And if the target object doesn’t implement any Interface, Spring AOP tries to generate dynamic proxy object instances for the target object using an open source dynamic bytecode generation Library called CGLIB (CodeGeneration Library).

Dynamic bytecode generation

Using dynamic bytecode generation technology is the principle of extended object behavior, we can inherit the extension of target object, to generate the corresponding subclasses, and subclasses can be extended by overriding the behavior of the parent class, as long as the implementation of crosscutting logic into subclasses, and then let the system using the extended a subclass of the target object, can achieve the same effect as the proxy pattern.

With dynamic bytecode enhancement, a module class can be extended even if it does not implement the corresponding interface, rather than being bound by the interface as dynamic proxies are. Extension cannot be subclassed if the class you want to extend, instance methods in the class, etc., are declared final.

AOP case

Exception handling

When an exception can be thrown from multiple places in the system, we might add exception handling logic at the top of each call, usually logging. These same logical implementations can be consolidated into one place for processing, which is essentially a cross-cutting concern.

The cache

Another major scenario for AOP applications is to transparently add caching support to the system. To prevent the cache implementation logic that needs to be added from affecting the implementation of the business logic, we can make the implementation of the cache independent of the implementation of the business objects, encapsulate the caching requirements in the system through AOP aspects, and only weave caching into a point in the system where caching support is definitely needed.

Spring Transaction Management

A transaction is a set of operations that access a data resource in a controlled manner. To ensure that the system state hosted by data resources is always “correct” before and after a transaction, transactions themselves hold 4 qualified properties Atomicity, Consistency, Isolation and persistence. This is also known as the ACID property of a transaction.

Spring transaction management is implemented through Spring AOP. The fundamental principle of Spring’s transaction framework design philosophy is to separate transaction management concerns from data access concerns.

  • When a transaction is defined at the business layer using the abstract API of the transaction, it is not necessary to care about what transaction resources the transaction will impose on it; the management of the different transaction resources will be taken care of by the corresponding framework implementation classes.
  • When accessing the data resources that may participate in the transaction at the data access layer, only the corresponding data access API is used for data access, and there is no need to care about how or whether the current transaction resource participates in the transaction. This will again be handled by the transaction framework class.

PlatformTransactionManager is the core of the Spring transaction abstraction architecture interface, its main function is to provide transaction demarcation for the application of unified way.

public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition var1) throws TransactionException; // Transaction commit void commit(TransactionStatus var1) throws TransactionException; // Transaction rollback void rollback(TransactionStatus var1) throws TransactionException; }Copy the code

Transaction management is typically placed in the Service layer and data access logic in the DAO layer. The goal is not to reduce the reusability of data access logic by putting transaction management code in the DAO layer, but also to decide whether to commit or roll back transactions at the Service layer based on the corresponding logic. A typical Service object might need to call the methods of multiple data access objects in the same business method.

Transaction isolation level

Database and program, also have the problem of concurrency, in the simultaneous existence of two or more than two database transaction environment, the same record or even different records will produce different results because of THE EXECUTION of SQL at different times, or even produce errors. The concept of database isolation level is then introduced, which is divided into dirty read, read/write commit, repeatable read, and serialization.

The following five constants are defined within TransactionDefinition to indicate the alternative isolation level.

  • ISOLATION_DEFAULT. If you specify isolation level ISOLATION_DEFAULT, the default isolation level for the database is used.
  • ISOLATION_READ_UNCOMMITTED. Corresponding to the Read Uncommited isolation level, dirty reads, unrepeatable reads, and magic reads cannot be avoided.
  • ISOLATION_READ_COMMITTED. Corresponding to the Read Commited isolation level, dirty reads can be avoided, but unrepeatable reads and phantom reads cannot be avoided.
  • ISOLATION_REPEATABLE_READ. The corresponding Repeatable Read isolation level can avoid dirty and unrepeatable reads, but not phantom reads.
  • ISOLATTON_SERIALTZABLE. The Serializable isolation level can avoid all dirty reads, unrepeatable reads, and phantom reads, but has the lowest concurrency efficiency.

Not all databases support all isolation levels. For example, Oracle database only supports read/write commit and serialization, and its default isolation level is read/write commit, while MySQL database’s default isolation level is repeatable read.

Propagation behavior of transactions

Propagation behavior refers to the invocation problem between methods. In most cases, we think that transactions should be all success or all failure at once.

TransactionDefinition provides the following options for the propagation behavior of transactions

Transaction implementation

Programmatic transaction management

Through the Spring programmatic transaction management there are two ways, either directly using PlatformrransactionManager, Transactionremplate or use more convenient.

TransactionTemplate is Spring provides programmatic transaction management template method, inherited DefaultTransactionDefinition. Transaction control properties can be provided directly through the TransactionTemplate itself.

Declarative transaction management

Annotation metadata driven declarative transaction management is the basic principle of metadata, the corresponding method of business affairs through annotations directly to the business or business methods of objects, and then during the term of business method, through reflection read annotation in the annotations on the business method contains metadata information, Ultimately, transaction management support is built for the business methods based on the information read.

Spring MVC

Spring MVC request flow

1. Request Spring’s DispatcherServlet. As with most Java-based Web frameworks, All Spring MVC requests go through a front Controller Servlet. The front controller is a common Web application pattern, where a single-instance Servlet delegates requests to other components of the application to perform the actual processing. In Spring MVC, the DispatcherServlet is the front-end controller. The job of the DispatcherServlet is to send requests to the Spring MVC controller (Controller). The controller is a Spring component that handles requests. There may be multiple controllers in a typical application and the DispatcherServlet needs to know which controller to send the request to. So the DispatcherServlet queries one or more handler mapping to determine where the request is going next.

2. The processor map makes decisions based on the URL information carried by the request. Once the appropriate controller is selected, the DispatcherServlet sends the request to the selected controller.

3. At the controller, the request unloads its load (user-submitted information) and waits patiently for the controller to process it. (In practice, well-designed controllers do little or no work themselves, instead delegating business logic to one or more service objects.) After the controller completes the logical processing, it usually generates some information that needs to be returned to the user and displayed on the browser. This information is called a model.

4. But it’s not enough to just return the user raw information — it needs to be formatted in a user-friendly way, usually HTML. So, the information needs to be sent to a view, usually a JSP. The last thing the controller does is wrap up the model data and label the view name for the rendered output. It then sends the request back to the DispatcherServlet with the model and view name. This way, the controller is not coupled to a particular view, and the view name passed to the DispatcherServlet does not directly represent a particular JSP. In fact, it is not even true that the controller is not coupled to a particular view, and the view name passed to the DispatcherServlet does not directly represent a particular JSP. In fact, it doesn’t even determine that the view is a JSP. Instead, it simply passes a logical name that will be used to find the real view that produced the result.

5. The DispatcherServlet will use the View Resolver to match the logical view name to a specific view implementation, which may or may not be a JSP. Now that the DispatcherServlet knows which view renders the result, the requested task is basically done.

6. Its final stop is the implementation of the view (probably a JSP), where it delivers model data. The requested task is completed. The view renders output using the model data, which is passed to the client through the response object.

Handle exceptions

Spring provides several ways to turn exceptions into responses: specific Spring exceptions are automatically mapped to specified HTTP status codes; The @responseStatus annotation can be added to the exception to map it to an HTTP status code; The @ExceptionHandler annotation can be added to the method to handle exceptions. The easiest way to handle an exception is to map it to an HTTP status code and place it in the response. Next, let’s look at how exceptions can be mapped to an HTTP status code.

Exceptions are typically thrown by Spring itself as a result of problems during DispatcherServlet processing or while performing validation. For example, if the DispatcherServlet unable to find a suitable for processing the request method of controller, so will be thrown NoSuchRequestHandlingMethodException abnormalities, The end result is a 404 status code response (Not Found). While these built-in mappings are useful, they are useless for exceptions thrown by the application. Fortunately, Spring provides a mechanism to map exceptions to HTTP status codes via the @responseStatus annotation.

REST 

Information-centric Representational State Transfer (REST)

  • Representational: REST resources can be represented in virtually any format, including XML, JSON (JavaScript Object Notation), and even HTML — whatever works best for the user of the resource;
  • State: When using REST, we care more about the State of the resource than the behavior we take on it;
  • Transfer: REST is about moving resource data in a declarative form from one application to another. .

REST is about moving the state of a resource from the server to the client (or vice versa) in a form that best suits the client or server.

Spring supports the following ways to create REST resources:

  • @pathVariable annotation, the controller can handle parameterized urls; With Spring’s views and View parser, resources can be represented in a variety of ways, including a View implementation that renders model data as XML, JSON, Atom, and RSS.
  • The @responseBody annotation and various HttpMethodConverter implementations can replace view-based rendering;
  • The @RequestBody annotation and the HttpMethodConverter implementation convert the incoming HTTP data into Java objects that are passed in to the controller’s handling methods; With RestTemplate, Spring applications can easily use REST resources.

Spring  WebFlux

JavaEE has been able to support responsive programming since the release of the Servlet3.1 specification. Spring5 released a new generation of responsive Web frameworks called Spring WebFlux.

Basic concept

In the case of a responsive framework, it is based on the idea of a responsive manifesto. The responsive manifesto is divided into four main ideas.

  • Sensitive: The system should be able to respond as quickly as possible.
  • Recoverable: The system may have problems during operation, but can remain responsive with strong fault tolerance and repair mechanisms.
  • Scalable: Responsive programming can vary according to its own pressure under any load, relieving the pressure on the server by reducing resources when there are few requests, and scalability in an affordable way by extending the service capacity through algorithms and software and hardware when there is a high load.
  • Message-driven: Reactive programming has asynchronous messaging mechanisms, where events collaborate via messages.

Based on this concept, responsive programming proposes various models to meet the concept of responsive programming, notably Reactor and RxJava, on which Spring5 builds WebFlux, which by default uses Reactor

Reactor model

Models in traditional programming

In this model, the number of requests is usually greater than the maximum number of threads in the system (denoted here as M). Assuming that most of the requests are time-consuming operations, M threads will not be able to respond to users in a timely manner after the number of requests increases. Obviously, a large number of threads have to wait in the request queue or be discarded by the system, so that for subsequent requests, the new thread will either wait for the old thread to complete or be discarded by the system. This scenario is often found in sites that require a lot of data flow, such as videos, games, graphics, and complex calculations.

Reactor model

First, the client registers the events it is interested in with the server, so that the client subscribes to the corresponding events and does not send requests to the server. When some registered event occurs on the client, it triggers the server’s response. When a server response is triggered, the server has a Selector thread that polls the server for events sent from the client, but does not process the Request. When it receives an event from the client, it finds the corresponding Request Handler and starts another thread to run the Handler. Because the Selector thread only polls and does not deal with complex business functions, it can respond to requests in real time after polling, very quickly. Since there are many kinds of events, there are also many request handlers, so there is also a need to distinguish the types of events, so there is a routing problem with Selector. As the request handler processes the business, the results are eventually converted into a data stream and sent to the client. Reactor is an event-based model. For server threads, it is also asynchronous. First, the Selector thread polls to the event, and then finds the processor to run the corresponding logic through routing.

Overview of Spring WebFlux

Prior to Servlet3.1, Web containers were developed based on blocking mechanisms, and after Servlet3.1(included), non-blocking specifications began. For high concurrency sites, the use of functional programming is more intuitive and easy, so it is very suitable for those who need high concurrency and a large number of requests of the Internet applications, especially those who need high-speed response and business logic requirements are not very strict sites, such as games, videos, news browsing websites.

In Spring WebFlux, there are two development approaches, one is a pattern similar to Spring MVC, and the other is functional programming.

Reactive programming is divided into Router Functions, Spring WebFlux and HTTP/Reactive Streams.

  • Router Functions: A routing distribution layer that determines which classes and methods are used to process event requests from clients based on the requested events. Obviously, in the Reactor schema, that’s what a Selector does.
  • Spring-webflux: a control layer similar to the Spring MVC framework. It mainly deals with the encapsulation before business logic and controls the return format of data flows.
  • HTTP/Reactive Streams: Is the process of transforming results into data Streams.

Flux and Mono by Reactor

These are classes that encapsulate data flows. Where Flux stores 0 N data flow sequences, which the reactive framework will send to the client one by one (please note not at once); Mono, on the other hand, stores a sequence of 101 data streams, and that’s the difference between them, and they can be converted to each other. Sometimes the responsiveness of the client is so different from that of the server that the client can be overwhelmed if the server loses a large amount of data to the client in a short period of time. In order to deal with this problem, would consider using reactive pull, and server-side data flow is divided into multiple sequences, a only sends a sequence of data flow to the client, when the client after processing the sequence, give the server sends a message, and then pull the second sequence, after the treatment, then sends a message to the service end, and so on, Until 0 to N data streams in Flux are fully processed, the client can retrieve data streams based on its response speed.

WebHandler interface

Instead of Spring MVC using DispactcherServlet, Spring WebFlux uses WebHandler. It is similar to DispatcherServlet in that they are very similar. WebHandler is an interface for which Spring WebFlux provides several implementation classes that can be used in different scenarios.

Run the process

Different from Spring MVC

Take a look at the Spring website for comparison

WebFlux is a non-blocking Web framework for a basic NIO implementation that supports a large number of concurrent connections.

Spring MVC is built on top of Servlet APL and uses a synchronous blocking I/O architecture, one request per thread model.

reference

Spring Boot 2.x Spring Boot 2.x