Book Image

Hands-On High Performance with Spring 5

By : Chintan Mehta, Subhash Shah, Pritesh Shah, Prashant Goswami, Dinesh Radadiya
Book Image

Hands-On High Performance with Spring 5

By: Chintan Mehta, Subhash Shah, Pritesh Shah, Prashant Goswami, Dinesh Radadiya

Overview of this book

While writing an application, performance is paramount. Performance tuning for real-world applications often involves activities geared toward detecting bottlenecks. The recent release of Spring 5.0 brings major advancements in the rich API provided by the Spring framework, which means developers need to master its tools and techniques to achieve high performance applications. Hands-On High Performance with Spring 5 begins with the Spring framework's core features, exploring the integration of different Spring projects. It proceeds to evaluate various Spring specifications to identify those adversely affecting performance. You will learn about bean wiring configurations, aspect-oriented programming, database interaction, and Hibernate to focus on the metrics that help identify performance bottlenecks. You will also look at application monitoring, performance optimization, JVM internals, and garbage collection optimization. Lastly, the book will show you how to leverage the microservice architecture to build a high performance and resilient application. By the end of the book, you will have gained an insight into various techniques and solutions to build and troubleshoot high performance Spring-based applications.
Table of Contents (14 chapters)

New features in the Spring Framework 5.0

The Spring Framework 5.0 is the first major upgrade in the Spring Framework, almost four years after the Spring Framework 4.0. In this time frame, one of the major developments has been the evolution of the Spring Boot project. We will discuss the new features in Spring Boot 2.0 in the next section. One of the biggest features of the Spring Framework 5.0 is reactive programming.

Core reactive programming features and support for reactive endpoints are available out of the box with the Spring Framework 5.0. The list of important changes includes the following:

  • Baseline upgrades
  • Reactive programming support
  • Core features upgrades
  • Spring Web MVC upgrades
  • Spring's new functional web framework, WebFlux
  • Modularity support
  • Kotlin language support
  • Improved testing support
  • Dropped or deprecated features

We will discuss these changes in detail in the following sections.

Baseline upgrades

The entire Spring Framework 5.0 has a JDK 8 and Jakarta EE 7 baseline. Basically, it means that to work on the Spring Framework 5.0, Java 8 is the minimum requirement.

Some of the important baseline Jakarta EE 7 specifications for the Spring Framework 5.0 are as follows:

  • The code base of the Spring Framework 5.0 is based on Java 8 source code level now. So, the code readability is improved using inferred generics, lambdas, and so on. It also has the stability in the code for conditional support for Java 8 features.
  • The Spring Framework requires at least Jakarta EE 7 API level to run any of the Spring Framework 5.0 applications. It requires Servlet 3.1, Bean Validation 1.1, JPA 2.1, and JMS 2.0.
  • The development and deployment process is fully compatible with JDK 9 as follows:
    • Compatible with classpath and module path, with stable automatic module names
    • The Spring Framework's build and test suite also pass on JDK 9, and by default, it can be run on JDK 8

Reactive programming support

The reactive programming model stands out among the most exciting feature of Spring 5.0. The Spring 5.0 Framework is based on a reactive foundation and is completely asynchronous and non-blocking. The new event-loop execution model can scale vertically using few threads.

The framework procures reactive streams to provide a system for conveying backpressure in a pipeline of reactive components. Backpressure is an idea that guarantees consumers do not get overpowered with data originating from different producers.

While Java 8 does not have built-in support for reactive programming, there are a number of frameworks that provide support for reactive programming:

  • Reactive Streams: Language-neutral attempt to define reactive APIs
  • Reactor: Java implementation of Reactive Streams provided by the Spring Pivotal team
  • Spring WebFlux: Enables the development of web applications based on reactive programming; provides a programming model similar to Spring MVC

Core features upgrades

As a part of the new features introduced in Java 8, the core of the Spring Framework 5.0 has been revised to provide some of the following key features:

  • Java 8 reflection enhancements include a provision of accessing method parameters in the Spring Framework 5.0 efficiently.
  • Provision of selective declaration support of Java 8 default methods in Spring Core interfaces.
  • Supports @Nullable and @NotNull annotations to explicitly mark nullable arguments and return values. This eliminates the cause of NullPointerExceptions at runtime and enables us to deal with null values at compile time.

For the logging side, the Spring Framework 5.0 provides out-of-the-box support with the Commons Logging Bridge module, named spring-jcl instead of the standard Commons Logging. Also, this new version will be able to detect Log4j 2.x, the Simple Logging Facade for Java (SLF4J), JUL (short for java.util.logging), without any extra amendments.

It also supports Resource abstraction by providing the isFile indicator for the getFile method.

Spring Web MVC upgrades

Spring 5.0 fully supports the Servlet 3.1 signature in Spring-provided Filter implementations. It also provides support for the Servlet 4.0 PushBuilder argument in Spring MVC controller methods.

Spring 5.0 also provides unified support for common media types through the MediaTypeFactory delegate, including the use of the Java Activation Framework.

The new ParsingPathMatcher will act as an alternative to AntPathMatcher, with more efficient parsing and extended syntax.

Spring 5.0 will also be providing support for ResponseStatusException as a programmatic alternative to @ResponseStatus.

Spring's new functional web framework – WebFlux

Another exciting feature to support reactive HTTP and WebSocket clients, the Spring Framework 5.0 provides the spring-webflux module. The Spring Framework 5.0 also provides support for REST, HTML, and WebSocket-style interactions for reactive web applications running on servers.

In spring-webflux, there are two major programming models on the server side:

  • Support for @Controller annotation including other Spring MVC annotations
  • Provision for functional style routing and handling with Java 8 Lambda

Spring spring-webflux also provides support for creating WebClient, which is reactive and non-blocking, as an alternative to RestTemplate.

Modularity support

The modular framework is trending on the Java platform. From Java 9, the Java platform became modular, and that helps to remove the flaws in encapsulation.

There are certain problems resulted to have modularity support, as explained here:

  • Java platform size: Since the last couple of decades, there was no need to add modularity support in Java. But there are many new lightweight platforms available on the market, like the Internet of Things (IoT), and Node.js. So, it was an urgent need to reduce the size of JDK version, because initial versions of JDK were less than 10 MB in size, whereas recent versions need more than 200 MB.
  • ClassLoader difficulty: When the Java ClassLoader searches for the classes, it will pick the class definition that is around itself, and immediately load the first class available. So, if there is the same class available in different JARs, then it is not possible for ClassLoader to specify the JAR from which the class is to be loaded.

To make Java applications modular, Open System Gateway initiative (OSGi) is one of the initiatives to bring modularity into the Java platform. In OSGi, each module is denoted as a bundle. Each bundle has its own life cycle, with different states as installed, started, and stopped.

The Jigsaw project is a primary motivation under the Java Community Process (JCP), to bring modularity into Java. Its main purpose is to define and implement a modular structure for JDK and to define a module system for Java applications.

Kotlin language support

The Spring Framework 5.0 introduces a statically typed JVM language support the Kotlin language (https://kotlinlang.org/), which enables code that is short, readable, and expressive. Kotlin is basically an object-oriented language that runs on top of the JVM, and also supports functional programming style.

With Kotlin support, we can dive into functional Spring programming, especially for functional web endpoints and bean registration.

In Spring Framework 5.0, we can write clean and readable Kotlin code for web-functional APIs as follows:

{
("/bank" and accept(TEXT_HTML)).nest {
GET("/", bankHandler::findAllView)
GET("/{customer}", bankHandler::findOneView)
}
("/api/account" and accept(APPLICATION_JSON)).nest {
GET("/", accountApiHandler::findAll)
GET("/{id}", accountApiHandler::findOne)
}
}

With the Spring 5.0 version, Kotlin's null-safety support is also provided with the indicating annotations using @NonNull, @Nullable, @NonNullApi, and @NonNullFields from the org.springframework.lang package.

There are some newly added Kotlin extensions that basically add function extensions to the existing Spring APIs. For example, the extension fun <T : Any> BeanFactory.getBean(): T from the package org.springframework.beans.factory adds the support in org.springframework.beans.factory.BeanFactory for searching a bean by just specifying the bean type as Kotlin's reified type parameter without class argument:

@Autowired
lateinit var beanFactory : BeanFactory

@PostConstruct
fun init() {
val bankRepository = beanFactory.getBean<BankRepository>()

}

One more extension can be found in org.springframework.ui, which provides operator overloading support to add an array-like getter and setter to the model interface:

model["customerType"] = "Premium"

Improved testing support

On the testing front, the Spring Framework 5.0 likewise accompanies JUnit Jupiter (https://junit.org/junit5/docs/current/user-guide/). It helps in writing tests and extensions in JUnit 5. It also gives a test engine to run Jupiter-constructed tests with respect to Spring and also provides a programming and extension model.

The Spring Framework 5.0 additionally underpins parallel test execution in the Spring TestContext Framework. For Spring WebFlux, spring-test likewise incorporates bolster for WebTestClient to integrate testing support for the reactive programming model.

There is no compelling reason to run a server for testing scenarios. By utilizing a new WebTestClient, which is like MockMvc, WebTestClient can bind specifically to the WebFlux server infrastructure using a mock request and response.

Dropped or deprecated features

In Spring 5.0, there are some of the packages that have been either removed or deprecated at the API level. The mock.staticmock package of the spring-aspects module is no longer available. The BeanFactoryLocator is also not available along with the bean.factory.access package. The NativeJdbcExtractor is also no longer available along with the jdbc.support.nativejdbc package. The packages web.view.tiles2, orm.hibernate3, and orm.hibernate4 are also replaced with Tiles 3 and Hibernate 5.

Many other bundles like JasperReports, Portlet, Velocity, JDO, Guava, XMLBeans are no longer supported in Spring 5. If you are utilizing any of the preceding bundles, it is advised to remain on the Spring Framework 4.3.x.