Spring 5 Framework with Reactive Programming

Spring 5Spring 5 Framework is a platform which can be used for the development of JAVA applications. This platform provides the users with the basic support and infrastructure to develop Java applications. It is a beneficial tool for the programmers, offering a number of benefits.

Here are some of the advantages of Spring 5

  • Without getting tangled with the transaction APIs, JAVA methods can be created and executed in the database transaction.
  • The need to deal with Servlet API in developing a local JAVA method, an HTTP endpoint is omitted.
  • The requirement of dealing or handling the JMS API in making a local JAVA method a message handler can be discarded.
  • The JMX API usage can be avoided to make a local JAVA method into a management operation.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

The features of using the Spring platform for developing Java applications are as follows:

About the Spring Framework 4.3

Spring Framework 4.3 is the last version of the spring framework platform before the spring framework platform 5.0. It had many enhancements in its working, processing, and components as compared to the earlier spring framework version 3.2. The key improvements were majorly in Core Container, Data Access, Caching Improvements, JMS Improvements, Web Improvements, WebSocket Messaging Improvements and Testing Improvements. Moreover, it had the support for new library and server generations.

Spring 5 Framework

23rd February 2017 marked the release of the Spring Framework 5.0. The most highlighted feature of Spring 5.0 is the reactive programming. More and more technologies are being witnessed for implementing reactive solutions, and the popularity of Reactive Programming is increasing day by day. This area of technology is evolving at greater pace. Spring Framework 5 uses Reactor, which is the complaint implementation of the reactive streams.

What Contributed to the Release of Spring 5 Framework

With every passing day, we experience change. This change occurs because everything needs to be enhanced. Products are improved to serve the consumers in a better way. The reasons behind the launch of Spring Framework 5.0, the latest version are:

  • Blocking IO
  • Latency Real Matters
  • Imperative code
  • Resource Utilization

Overview of Spring Framework 5.0

Like all other spring framework versions, spring framework 5.0 provides several facilities that help a programmer develop JAVA applications with ease. A central Servlet around which Spring Framework 5.0 is designed, dispatches requests to controllers. The dispatcher Servlet of the latest version of Spring is not like the dispatchers of the previous versions. The Spring LoC container has a dispatcher integrated with it, this lets the developer an access to all other features of Spring 5.

Processing Sequence

As now that we know the reason behind the release of the new version, it is time we talk about its working.

The Spring 5 processing follows the following sequence

Step 1: Request received by DispatcherServlet.
Step 2: To select the controller for HandlerMapping, DispatcherServlet dispatches the task. HandlerMapping later chooses the controller that the incoming request URL is mapped to. It then returns the chosen Handler and Controller to DispatcherServlet.
Step 3: The task of execution of business logic of controller are then dispacted by DispatcherServlet to the Handler Adapter.
Step 4: The HandlerAdapter then calls the business logic step of the controller.
Step 5: The execution of the business logic is carried out by the Controller. The processing of the resulting model is set and in result, returns the logical name of the view to HandlerAdapter.
Step 6: To resolve task of the view corresponding ViewResolver, it is dispatched by DispatcherServle. The mapped view and name of the view is then returned by the ViewResolver.
Step 7: The rendering process is returned to the view by DispatcherServlet.
Step 8: The response is returned by the view after it renders model data.

Components and their Working

1. HandlerMapping

Usually org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping is processed for this use. @RequestMapping annotation is then read by the class from the Controller and makes use of the method of Controller which corresponds to the URL as Handler Class.
In Spring3.1, RequestMappingHandlerMapping is enabled automatically when is set in Bean definition file read by DispatcherServlet. (Take reference from MVC framework to understand the settings that get enabled on the use of annotation.)

2.  HandlerAdapter

Usually org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter is used. The method of handler class (Controller) picked by HandlerMapping is called by RequestMappingHandlerAdapter.
In Spring 3.1, configures this class by default as well.

3. ViewResolver

Usually (When JSP is used) the following comes in action org.springframework.web.servlet.view.InternalResourceViewResolver On the other hand for template engine tiles, org.springframework.web.servlet.view.tiles3.TilesViewResolver is used. When the stream is to be returned for file download org.springframework.web.servlet.view.BeanNameViewResolver, this can be used.

ViewResolve’s type is selected relying on the kid of the view that is to be returned. When multiple types of views are to be handled, we require multiple definitions of ViewResolver.

Example: Using multiple ViewResolver is the screen application for that file download process already exists.
For screen (JSP), InternalResourceViewResolver is used to resolve the view and for File download, BeanNameViewResolver is being used.

4. View

This component of the spring framework 5.0 depends upon the type of response to be returned. org.springframework.web.servlet.view.JstlView is used when JSP Needs to be returned. Spring Framework dependent libraries are to be handled when Spring Framework doesn’t provide the view, we have to implement view interface with an extended class.

Major Changes

The major features that offer great improvements are;

  • JDK baseline update
  • Core framework revision
  • Core container updates
  • Functional programming with Kotlin
  • Reactive Programming Model
  • Testing improvements
  • Library support
  • Discontinued support

Spring 5 Framework offers the best facilities for the programmers out there who wish to develop JAVA applications. It is a beneficial tool that will help the programmers of the world do wonders in their field. As this is a popular field of interest and contributes a significant part to the advancement of the world, Spring 5 Framework is just the beginning. More and more technologies are emerging from all around the world but Spring Framework is the best technological platform for the programmers to perform and come up with some best applications without going through the tough hurdles of the journey that existed before the release of this highly efficient JAVA application developer platform.

New Features added to Spring 5

Spring Framework is a conducive platform facilitating all the JAVA programming fanatics out there. It is a tool that helps the JAVA programmers develop Java applications with great ease and convenience.

This new version comes with lots of new and advanced features. The list of the features added in this new version is as follows:

  • JDK baseline update
  • Core framework revision
  • Core container updates
  • Functional programming with Kotlin
  • Reactive Programming Model
  • Improved Testing
  • Library support

Now, let’s get into the details of each of these added new features in the Spring Framework 5.0 .

JDK Baseline Update

The codebase of this new version of the Spring 5 Framework runs entirely on JAVA 8. To work with this new framework version, a programmer must be well-acquainted with the JAVA 8 basics as this is the core requirement for using the spring framework 5.0 . The first choice for this version was JAVA 9, but due to the delay of the release of JAVA 9, the latest spring version works with the JAVA 8. This version is designed in a way that it will be cent percent compatible with the latest JAVA 9. So the programmers who will work on JAVA 9 and develop an upper hand over the JAVA 9 skills can operate this spring 5 with it.

Core Framework Revision

As the Spring 5 Framework is compatible with JAVA 8 and does not support other prior JAVA versions, the core of the spring framework had to be revised. This was done so that the spring framework could work easily with the updates and changes made in the JAVA 8. The revisions made to the core of the framework are as follows:

  • The method parameters can be very efficiently accessed using this latest version of spring framework.
  • Selective declarations that are built on JAVA 8 are now provided by the Core Spring interfaces.
  • @Nullable and @NotNull annotations to explicitly mark nullable arguments and return values through which dealing with the null values at compile time rather than throwing NullPointerExceptions at runtime is enabled.

Spring Framework 5.0  has Commons Logging bridge module, called spring-jcl despite of the standard Commons Logging on the logging front. Auto detection of Log4j 2.x, SLF4J, JUL ( java.util.logging) without any extra bridges can be carried out using the Spring 5 Framework. Furthermore, defensive programming gets boosted with the Resource abstraction providing the isFile indicator for the getFile method.

Core Container Updates

The candidate component index has replaced classpath scanning in the Spring Framework 5.0 . The reason why the classpath scanning has been replaced is that the candidate component index is a shortcut for the candidate component identification step in the classpath scanner. For the current project, an application build task can define its own META-INF/spring.components. When the compilation process starts, the source model has to be introspected while, JPA entities and Spring Components are flagged. However, this change is not so beneficial for projects that contain less than 200 classes but has outstanding benefits for projects that are larger and contain more than 200 classes.

A good news for the programmers with this latest version of Spring Framework 5.0 is that the startup time for applications is greatly reduced. Apparently 20 or 30 seconds is a small duration but when the queues are longer it looks very long. Component index can help in this regard.

Now @Nullable annotations are also utilized as indicators for other injection points. Using @Nullable can cause an obligation which will return a null value. Earlier the only way to do it was Nullable or Checker’s Nullable. This change has several other benefits that include; Implementation of functional programming style in GenericApplicationContext and AnnotationConfigApplicationContext, consistent detection of the transaction, caching, async annotations on interface methods and XML configuration namespaces streamlined towards unversioned schemas.

Functional Programming with Kotlin

Kotlin language, a language that supports the functional programming style and is object oriented, by JetBrains is supported by the Spring Framework 5.0 . This language runs on top of JVM but it is not just restricted to it. The benefit of using this language for developing JAVA applications is that developers can dive into functional Spring programming, in particular for functional Web endpoints and bean registration.

For example

For a Web functional API, a developer can use the following code;

 
{
("/movie" and accept(TEXT_HTML)).nest {
GET("/", movieHandler::findAllView)
GET("/{card}", movieHandler::findOneView)
}
("/api/movie" and accept(APPLICATION_JSON)).nest {
GET("/", movieApiHandler::findAll)
GET("/{id}", movieApiHandler::findOne)
}
}

For registering as bean rather than XML, the following code in the Kotlin language can be used;

 
{
val context = GenericApplicationContext {
registerBean()
registerBean{ Cinema(it.getBean()) }
}

Reactive Programming Model

The most highlighted feature of the latest version of the Spring Framework is the new reactive stack Web framework. Reactive is being called the update that takes us to future. This area of technology is gaining popularity with every passing day which is the reason why Spring Framework 5.0 has been launched with the capability of reactive programming. This addition makes the latest version of Spring Framework convenient for event-loop style processing which enables scaling with a small number of threads.

This is an API specification that the engineers came up with through the sources such as Pivotal, Red Hat, Netflix, Oracle, Typesafe, Twitter, and Spray.io. This feature provides a simple common API for implementing reactive programming. Examples of such implementations include JPA for Hibernate, here the JPA is the API, and Hibernate is the implementation.

The Project Reactor is what implements the API specifications for the reactive stream. The project reactor provides the base for streaming support in Spring Framework 5.0 is developed on.

WebSocket and Reactive HTTP clients are supported by Spring Framework 5.0. This is possible because the latest version has a new spring-webflux module. Moreover, the servers which have REST, HTML and WebSocket support are on which the reactive web applications run.

Programming models on the server-side in spring-webflux include:

  • Annotation-based with @Controller and the other annotations of Spring MVC
  • Functional style routing and handling with Java 8 lambda

For Example:
In this example, Spring Webflux is being used for creatingWebClient, which is reactive and nonblocking. And also serves as the replacement of Resttemplate:

 WebClientwebClient = WebClient.create();
Mono person = webClient.get()
.uri("http://localhost:8080/movie/42")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.then(response ->response.bodyToMono(Movie.class));
WebClientwebClient = WebClient.create();
Mono person = webClient.get()
.uri("http://localhost:8080/movie/42")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.then(response ->response.bodyToMono(Movie.class));

Improved Testing

Junit 5 Jupiter can now be used to write tests and extensions in JUnit 5 in the latest version of Spring Framework. Moreover, a test engine to run Jupiter based test is also provided by the Jupiter sub-project. Also, the new updates in Spring Framework support parallel text execution.

WebTestClientthat is used for integrating testing support for Spring WebFlux is also provided for the reactive programming addition in the latest framework. WebTestClient, similar toMockMvc but unlike MockMvc does not require a running server. A WebTestClient can also be complied with help of the WebFlux server using a sample request and response.

Library Support

The new version has an upgraded library as well. These are the following upgraded library versions that are supported by Spring Framework 5.0:

  • Jackson 2.6+
  • EhCache 2.10+ / 3.0 GA
  • Hibernate 5.0+
  • JDBC 4.0+
  • XmlUnit 2.x+
  • OkHttp 3.x+
  • Netty 4.1+

Thus, these are some of the major additions made to the Spring Framework and make Spring Framework 5.0 a much better platform to develop JAVA applications. Not only additions have been made to the Spring Framework,but some of the offered features have been discontinued too.

The packages are no longer supported at the API level are:

  • beans.factory.access
  • jdbc.support.nativejdbc
  • mock.staticmock of the spring-aspects module.
  • web.view.tiles2M. Now Tiles 3 is the minimum requirement.
  • orm.hibernate3 and orm.hibernate4. Now, Hibernate 5 framework is supported.

The packages discontinued at the library level include:

  • Portlet
  • Velocity
  • JasperReports
  • XMLBeans
  • JDO
  • Guava

Happy Spring learning with us!!!

Previous

3 Comments

  1. Padam Dhariwal September 13, 2017
  2. Dinesh September 14, 2017
  3. David September 26, 2017