Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On High Performance with Spring 5
Hands-On High Performance with Spring 5

Hands-On High Performance with Spring 5: Techniques for scaling and optimizing Spring and Spring Boot applications

Arrow left icon
Profile Icon Mehta Profile Icon Dinesh Radadiya Profile Icon Prashant Goswami Profile Icon Subhash Shah Profile Icon Shah +1 more Show less
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Jun 2018 408 pages 1st Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Mehta Profile Icon Dinesh Radadiya Profile Icon Prashant Goswami Profile Icon Subhash Shah Profile Icon Shah +1 more Show less
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Jun 2018 408 pages 1st Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Hands-On High Performance with Spring 5

Exploring Spring Concepts

The Spring Framework provides extensive support for managing large enterprise Java applications and also addresses the complexities of enterprise application development. Spring provides a complete set of API and configuration models for modern enterprise applications so that programmers just need to focus on the business logic of the application.

Introduced as a lightweight framework, the Spring Framework was aimed at providing a way of making the development of Java enterprise applications easy and simple.

This chapter will help you gain a better understanding of the core features of the Spring Framework. We will start with an introduction to the Spring Framework. This chapter will also give you a clear understanding of every major module of the Spring Framework. After having a quick look at the important modules in the Spring Framework, we will dive into the world of Spring projects. We will also have a clear understanding of the Spring Inversion of Control (IoC) container. At the end, we will have a look at the new features and enhancements introduced in Spring 5.0.

In this chapter, we will be looking at the following topics:

  • Introducing the Spring Framework
  • Understanding Spring modules
  • Spring projects
  • Spring IoC container
  • New features in Spring Framework 5.0

Introducing the Spring Framework

The Spring Framework is one of the most popular open source Java application frameworks and IoC containers. Spring was originally developed by Rod Johnson and Jurgen Holler. The first milestone version of Spring Framework was released in March 2004. Though it has been a decade and a half, the Spring Framework remains the framework of choice to build any Java application.

The Spring Framework provides comprehensive infrastructure support for developing enterprise Java applications. So, developers don't need to worry about the infrastructure of the application; they can focus on the business logic of the application, rather than handling the configuration of the application.

All infrastructure, configuration, and meta configuration files, either Java-based or XML-based, are handled by the Spring Framework. So, this framework gives you more flexibility in building an application with a Plain Old Java Object (POJO) programming model rather than a non-invasive programming model.

The Spring IoC container forms the core of the entire framework by putting together any application's various components. Spring Model-View-Controller (MVC) components can be used to build a very flexible web tier. The IoC container simplifies the development of the business layer with POJOs.

Problems with EJB

In the early days, it was very difficult for programmers to manage enterprise applications, because the enterprise Java technologies like Enterprise JavaBeans (EJB) were much heavier to provide the enterprise solutions to programmers.

When EJB technology was first announced, it was offering a distributed component model that would allow the developers to focus only on the business side of the system while ignoring the middleware requirements, such as wiring of components, transaction management, persistence operations, security, resource pooling, threading, distribution, remoting, and so on; however, it was a very cumbersome process for developing, unit testing, and deploying EJB applications. Some of the following complexities were faced while using EJB:

  • Forcing implementation of unnecessary interfaces and methods
  • Making unit testing difficult, especially outside the EJB container
  • Inconveniences in managing deployment descriptors
  • Tedious exception handling

At that time, Spring was introduced as an alternative technology especially made for EJB, because Spring provided a very simple, leaner, and lighter programming model compared with other existing Java technologies. Spring makes it possible to overcome the preceding complexities, and also to avoid the use of some other heavier enterprise technologies by using many available design patterns. The Spring Framework focused on the POJO programming model rather than a non-invasive programming model. This model provided the simplicity to the Spring Framework. It also empowered ideas such as the dependency injection (DI) pattern and Aspect-Oriented Programming (AOP), using the proxy pattern and decorator pattern.

Simplifying implementation using POJO

The most important advantage of the POJO programming model is that coding application classes is very fast and simple. This is because classes don't need to depend on any particular API, implement any special interface, or extend from a particular framework class. You do not have to create any special callback methods until you really need them.

Benefits of the Spring Framework

The important benefits of the Spring Framework are as follows:

  • No need to reinvent the wheel
  • Ease of unit testing
  • Reduction in implementing code
  • Inversion of control and API
  • Consistency in transaction management
  • Modular architecture
  • Up to date with time

Let's discuss each in detail.

No need to reinvent the wheel

No need to reinvent the wheel is one of the most important benefits that developers can leverage from the Spring Framework. It facilitates the practical use of the well-known technologies, ORM frameworks, logging frameworks, JEE, JDK timers, Quartz, and so on. So, developers don't have to learn any new technologies or frameworks.

It facilitates good programming practices, such as programming using interfaces instead of classes. Spring enables developers to develop enterprise applications using POJO and Plain Old Java Interface (POJI) model programming.

Ease of unit testing

If you want to test the applications developed using Spring, it is quite easy. The main reason behind this is that the environment-dependent code is available in this framework. Earlier versions of EJBs were very difficult to unit test. It was difficult to even run EJBs outside the container (as of version 2.1). The only way to test them was to deploy them in a container.

The Spring Framework introduced the DI concept. We will discuss DI in complete detail in Chapter 2, Spring Best Practices and Bean Wiring Configurations. The DI enables unit testing. This is done by replacing the dependencies with their mocks. The entire application need not be deployed to unit test.

Unit testing has multiple benefits:

  • Improving the productivity of programmers
  • Detecting defects at earlier stages, thereby saving the cost of fixing them
  • Preventing future defects by automating unit tests in applications that are running in continuous integration (CI) builds

Reduction in implementing code

All application classes are simple POJO classes; Spring is not invasive. It does not require you to extend framework classes or implement framework interfaces for most use cases. Spring applications do not require a Jakarta EE application server, but they can be deployed on one.

Before the Spring Framework, typical J2EE applications contained a lot of plumbing code. For example:

  • Code for getting a database connection
  • Code for handling exceptions
  • Transaction management code
  • Logging code and a lot more

Let's look at the following simple example of executing a query using PreparedStatement:

PreparedStatement st = null;
try {
st = conn.prepareStatement(INSERT_ACCOUNT_QUERY);
st.setString(1, bean.getAccountName());
st.setInt(2, bean.getAccountNumber());
st.execute();
}
catch (SQLException e) {
logger.error("Failed : " + INSERT_ACCOUNT_QUERY, e);
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
logger.log(Level.SEVERE, INSERT_ACCOUNT_QUERY, e);
}
}
}

In the preceding example, there are four lines of business logic and more than 10 lines of plumbing code. The same logic can be applied in a couple of lines using the Spring Framework, as follows:

jdbcTemplate.update(INSERT_ACCOUNT_QUERY,
bean.getAccountName(), bean.getAccountNumber());

Using Spring, you can use a Java method as a request handler method or remote method, like a service() method of a servlet API, but without dealing with the servlet API of the servlet container. It supports both XML-based and annotation-based configuration.

Spring enables you to use a local Java method as a message handler method, without using a Java Message Service (JMS) API in the application. Spring serves as a container for your application objects. Your objects do not have to worry about finding and establishing connections with each other. Spring also enables you to use the local Java method as a management operation, without using a Java Management Extensions (JMX) API in the application.

Inversion of control and API

Spring also helps developers to get rid of the necessity of writing a separate compilation unit, or a separate class loader to handle exceptions. Spring converts technology-dependent exceptions, particularly thrown by Java Database Connectivity (JDBC), Hibernate or Java Data Objects (JDO), into unchecked and consistent exceptions. Spring does this magic using inversion of control and APIs.

Also, it uses IoC for DI, which means aspects can be configured normally. If we want to add our own behavior, we need to extend the classes of the framework or plug in our own classes. The following is a list of advantages for this kind of architecture:

  • Decoupling the execution of a task from its implementation
  • Making it easier to switch between different implementations
  • Greater modularity of a program
  • Greater ease in testing a program by isolating a component or mocking it
  • Dependencies and allowing components to communicate through contracts

Consistency in transaction management

Spring also provides support for transaction management with consistency. It provides an easy and flexible way to configure local transactions for small applications as well as global transactions for large applications using the Java Transaction API (JTA). So we do not need to use any third-party transactional API to execute a database transaction; Spring will take care of it with the transaction management feature.

Modular architecture

Spring provides a modular architecture that helps developers to identify the packages or classes which are to be used and which are to be ignored. Hence, in this way, we can keep only those things which we really need. So that makes it easy to identify and utilize the usable packages or classes even if there are many packages or classes.

Spring is a powerful framework that addresses many common problems in Jakarta EE. It includes support for managing business objects and exposing their services to presentation tier components.

Spring instantiates the beans and injects the dependencies of your objects into the application it serves as a life cycle manager of the beans.

Up to date with time

When the first version of the Spring Framework was built, its main focus was to make applications testable. There were also new challenges in the later versions, but the Spring Framework managed to evolve and stay ahead and on track with the architectural flexibility and modules that are offered. Some examples are listed as follows:

  • The Spring Framework introduced a number of abstractions ahead of Jakarta EE to keep the application decoupled from the specific implementation
  • The Spring Framework also provided transparent caching support in Spring 3.1
  • Jakarta EE was introduced with JSR-107 for JCache in 2014, so it was provided in Spring 4.1

Another major evolution that Spring was involved with was to provide different Spring projects. The Spring Framework is just one of the many projects among Spring projects. The following example illustrates how the Spring Framework managed to remain up to date in terms of Spring projects:

  • As architecture evolved toward cloud and microservices, Spring came up with new cloud-oriented Spring projects. The Spring Cloud project simplifies development and deployment of microservices.
  • To build Java batch applications, a new approach was introduced as the Spring Batch project by the Spring Framework.

In the next section, we will dive deep into the different Spring Framework modules.

Understanding Spring modules

Spring provides a modular architecture that is one of the most important reasons for the popularity of the Spring Framework. Its layered architecture enables integration of other frameworks easily and without hassle. These modules provide everything that a developer may need to use in enterprise application development. The Spring Framework is organized into 20 different modules that are built on the top of its Core Container.

The following diagram illustrates different Spring modules organized in a layered architecture:

Spring Framework modules

We will start with discussing the Core Container before moving on to other modules.

Core Container

The Spring Core Container provides the core features of the Spring Framework, namely as Core, Beans, Context, and Expression Language, the details of which are as follows:

Artifact

Module Usage

spring-core

This module facilitates all the utilities used by other modules and it also provides a way for managing the different bean life cycle operations.

spring-beans

This module is mainly used to decouple code dependencies from your actual business logic and eliminates the use of singleton classes using DI and IoC features.

spring-context

This module provides features like internationalization, and resource loading, and also underpins Java EE features like EJB, JMS, and remoting.

spring-expression

This module provides support for accessing properties of beans at runtime and also allows us to manipulate them.

Crosscutting concerns

Crosscutting concerns are applicable to all the layers of an application, including logging and security, among others. Important Spring modules related to crosscutting concerns are as follows:

Artifact Module Usage

spring-aop

This module is mainly used to perform the tasks which are common amongst different parts of a system like transaction management, logging, and security. To enable this we can implement method-interceptors and pointcuts.

spring-aspects

This module is used to integrate any custom object type. It is possible using AspectJ, and the main use of this module is to integrate the objects which are not in the control of the container.

spring-instrument

This module is used to measure the application's performance and also helps to perform error diagnosis using trace information.

spring-test

This module is used to integrate testing support in a Spring application.

Data Access/Integration

The Data Access/Integration layer in applications interacts with the database and/or the external interfaces. It consists of JDBC, ORM, OXM, JMS, and Transaction modules. These modules are spring-jdbc, spring-orm, spring-oxm, spring-jms, and spring-tx.

Web

The Web layer contains the Web, Web-MVC, Web-Socket, and other Web-Portlet modules. The respective module names are spring-web, spring-webmvc, spring-websocket, spring-webmvc-portlet.

In the next section, we will go through different kinds of Spring projects.

Spring projects

The Spring Framework provides different kinds of projects for different infrastructure needs, and also helps to explore solutions to other problems in the enterprise application: deployment, cloud, big data, and security, among others.

Some of the important Spring projects are listed as follows:

  • Spring Boot
  • Spring Data
  • Spring Batch
  • Spring Cloud
  • Spring Security
  • Spring HATEOAS

Let's discuss them in detail.

Spring Boot

Spring Boot provides support to create standalone, production-grade, Spring-based applications that you can just run.

Spring Boot also provides some of the following features out of the box, by taking an opinionated view of how applications have to be developed:

  • Provides support for developing standalone Spring applications
  • Embeds Tomcat, Jetty, or Undertow directly, with no need to deploy WAR files
  • Allow us to externalize configuration to work in different environments with the same application code
  • Simplifies Maven configuration by providing opinionated starter POMs
  • Eliminates the need for code generation and the requirement for XML configuration
  • Provides support for production features like metrics, health checks, and application monitoring

We will look at Spring Boot in depth in Chapter 12, Spring Boot Microservice Performance Tuning.

Spring Data

The main goal of the Spring Data project is to provide an easy and consistent Spring-based model to access data and other special features, to manipulate SQL-and NoSQL-based data stores. It also tries to provide an easy way to use data access technologies, map-reduce frameworks, relational and non-relational databases, and cloud-based data services.

Some of the important features are as follows:

  • Provides support for integration with custom repository code
  • Provides repository and object-mapping abstractions by deriving dynamic queries using repository method names
  • Advanced integration support with Spring MVC controllers
  • Advanced support for transparent auditing features such as created by, created date, last changed by, and last changed date
  • Experimental integration support for cross-store persistence

Spring Data provides integration support for the following data sources:

  • JPA
  • JDBC
  • LDAP
  • MongoDB
  • Gemfire
  • REST
  • Redis
  • Apache Cassandra
  • Apache Solr

Spring Batch

Spring Batch facilitates essential processing for large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management, by providing reusable functions. It also provides more advanced technical services and features that will enable extremely high-volume and high-performance batch jobs using optimization and partitioning techniques.

Important features of Spring Batch are as follows:

  • The ability to process data in chunks
  • The ability to start, stop and restart jobs, including the ability to restart, in the case of failed jobs, from the point where they failed
  • The ability to retry steps or to skip steps on failure
  • Web-based administration interface

Spring Cloud

It is not an overstatement to say the world is moving to the cloud.

Spring Cloud provides tools for developers to build common patterns in distributed systems. Spring Cloud enables developers to quickly build services and applications that implement common patterns to work in any distributed environment.

Some of the common patterns implemented in Spring Cloud are as follows:

  • Distributed configuration
  • Service registration and discovery
  • Circuit breakers
  • Load balancing
  • Intelligent routing
  • Distributed messaging
  • Global locks

Spring Security

Authentication and authorization are the essential parts of enterprise applications, both web applications and web services. Spring Security is a powerful and highly customizable authentication and access control framework. Spring Security focuses on providing declarative authentication and authorization to Java applications.

Important features in Spring Security are as follows:

  • Comprehensive support for both authentication and authorization
  • Good support for integration with servlet APIs and Spring MVC
  • Module support for integration with Security Assertion Markup Language (SAML) and Lightweight Directory Access Protocol (LDAP)
  • Providing support for common security attacks such as Cross-Site Forgery Request (CSRF), session fixation, clickjacking, and so on

We will discuss how to secure web applications with Spring Security in Chapter 4, Spring MVC Optimization.

Spring HATEOAS

The main purpose of Hypermedia As The Engine Of Application State (HATEOAS) is to decouple the server (the service provider) from the client (the service consumer). The server provides the client with information on other possible actions that can be performed on the resource.

Spring HATEOAS provides a HATEOAS implementation, especially for the REpresentational State Transfer (REST) services implemented with Spring MVC.

Spring HATEOAS has the following important features:

  • A simplified definition of links pointing to service methods, making the links less fragile
  • Support for JSON and JAXB (XML-based) integration
  • Support for hypermedia formats such as Hypertext Application Language (HAL)

In the next section, we will understand the mechanism of Spring's IoC container.

Spring's IoC container

Spring's IoC container is built as the core module of the Spring architecture. IoC is also known as DI. It is a design pattern which eliminates the dependency of the code to provide ease in managing and testing the application. In DI, the objects themselves characterize their dependencies with the other objects they work, just through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is created or returned from a factory method.

The container is then responsible to inject those dependencies when it creates the bean. This process is basically the inverse (so it is known as IoC) of the bean itself controlling the instantiation or location of its dependencies, by using the direct construction of classes, or a mechanism.

There are two main base packages of the Spring Framework's IoC container: org.springframework.beans, and org.springframework.context. The BeanFactory interface provides some of the advanced-level configuration mechanisms to manage any type of object. ApplicationContext includes all the functionalities of BeanFactory, and acts as a subinterface of it. In fact, ApplicationContext is also recommended over BeanFactory, and provides more supporting infrastructure that enables: easier integration with Spring's AOP features and transaction; message resource handling in terms of internationalization and event publication; and application layer-specific contexts such as WebApplicationContext for use in web applications.

The interface org.springframework.context.ApplicationContext is represented as the Spring IoC container, and it is in complete control of a bean's life cycle and responsible for instantiating, configuring, and assembling the beans.

The container gets all the instructions to instantiate, configure, and assemble, by scanning bean configuration metadata. The configuration metadata can be represented using the following methods:

  • XML-based configuration
  • Annotation-based configuration
  • Java-based configuration

We will learn these methods in more detail in Chapter 2, Spring Best Practices and Bean Wiring Configurations.

The following diagram represents a simple representation of the Spring Container process towards creating a fully configured application:

The Spring IoC container

The following example shows the basic structure of XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- All the bean configuration goes here -->
<bean id="..." class="...">

</bean>

<!-- more bean definitions go here -->

</beans>

The id attribute is a string that you use to identify the individual bean definition. The class attribute defines the type of bean, and uses the fully qualified class name. The value of the id attribute refers to collaborating objects.

What are Spring beans?

You can consider a Spring bean as a simple Java object, instantiated, configured, and managed by a Spring IoC container. It is called a bean instead of an object or component because it is a replacement for complex and heavy enterprise JavaBeans with respect to the origin of the framework. We will learn more about Spring bean instantiation methods in Chapter 2, Spring Best Practices and Bean Wiring Configurations.

Instantiating a Spring container

For creating bean instances, we first need to instantiate a Spring IoC container by reading the configuration metadata. After initialization of an IoC container, we can get the bean instances using the bean name or ID.

Spring provides two types of IoC container implementations:

  • BeanFactory
  • ApplicationContext

BeanFactory

The BeanFactory container acts as the simplest container providing basic support for DI, and it is defined by the org.springframework.beans.factory.BeanFactory interface. BeanFactory is responsible to source, configure, and assemble the dependencies between objects. BeanFactory mainly acts as an object pool, where object creation and destruction is managed through configuration. The most popular and useful implementation of BeanFactory is the org.springframework.context.support.ClassPathXmlApplicationContext. The ClassPathXmlApplicationContext uses XML configuration metadata to create a fully configured application.

The following sample defines a simple HelloWorld application using ClassPathXmlApplicationContext. The content of Beans.xml looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bankAccount"
class="com.packt.springhighperformance.ch1.bankingapp.BankAccount">
<property name="accountType" value="Savings Bank Account" />
</bean>
</beans>

The preceding XML code represents the content of bean XML configuration. It has a single bean configured, which has a single property with the name message. It has a default value set for the property.

Now, the following Java class represents bean configured in the preceding XML.

Let's have a look at HelloWorld.java:

package com.packt.springhighperformance.ch1.bankingapp;

public class BankAccount {
private String accountType;

public void setAccountType(String accountType) {
this.accountType = accountType;
}

public String getAccountType() {
return this.accountType;
}
}

At the end, we need to use ClassPathXmlApplicationContext to create the HelloWorld bean and invoke a method in the created Spring bean.

Main.java looks as follows:

package com.packt.springhighperformance.ch1.bankingapp;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.
support.ClassPathXmlApplicationContext;

public class Main {

private static final Logger LOGGER = Logger.getLogger(Main.class);

@SuppressWarnings("resource")
public static void main(String[] args) {
BeanFactory beanFactory = new
ClassPathXmlApplicationContext("Beans.xml");
BankAccount obj = (BankAccount) beanFactory.getBean("bankAccount");
LOGGER.info(obj.getAccountType());
}
}

ApplicationContext

The ApplicationContext container provides support to access application components using BeanFactory methods. This includes all functionality of BeanFactory. In addition, ApplicationContext can also perform more enterprise functionalities, like transaction, AOP, resolving text messages from properties files, and pushing application events to interested listeners. It also has the ability to publish events to the registered listeners.

The mostly-used implementations of ApplicationContext are FileSystemXmlApplicationContext, ClassPathXmlApplicationContext, and AnnotationConfigApplicationContext.

Spring also provides us with a web-aware implementation of the ApplicationContext interface, as shown:

  • XmlWebApplicationContext
  • AnnotationConfigWebApplicationContext

We can use either one of these implementations to load beans into a BeanFactory; it depends upon our application configuration file locations. For example, if we want to load our configuration file Beans.xml from the filesystem in a specific location, we can use a FileSystemXmlApplicationContext class that looks for the configuration file Beans.xml in a specific location within the filesystem:

ApplicationContext context = new
FileSystemXmlApplicationContext("E:/Spring/Beans.xml");

If we want to load our configuration file Beans.xml from the classpath of our application, we can use ClassPathXmlApplicationContext class provided by Spring. This class looks for the configuration file Beans.xml anywhere in the classpath, including JAR files:

ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");

If you are using a Java configuration instead of an XML configuration, you can use AnnotationConfigApplicationContext:

ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);

After loading the configuration files and getting an ApplicationContext, we can fetch beans from the Spring container by calling the getBean() method of the ApplicationContext:

BankAccountService bankAccountService =
context.getBean(BankAccountService.class);

In the following section, we will learn about the Spring bean life cycle, and how a Spring container reacts to the Spring bean to create and manage it.

Spring bean life cycle

The factory method design pattern is used by the Spring ApplicationContext to create Spring beans in the container in the correct order, as per the given configuration. So, the Spring container is responsible for managing the life cycle of the bean, from creation to destruction. In a normal Java application, a new keyword of Java is used to instantiate the bean, and it's ready to use. Once the bean is no longer in use, it's eligible for garbage collection. But in a Spring container, the life cycle of the bean is more elaborate.

The following diagram illustrates the life cycle of a typical Spring bean:

Spring bean life cycle

In the next section, we will see the new features of the Spring Framework 5.0.

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.

Summary

In this chapter, we gained a clear understanding of the core features of the Spring Framework. We also covered different kinds of Spring modules. After that, we went through different types of Spring projects in the Spring Framework. We also understood the mechanisms of a Spring IoC container. At the end of the chapter, we looked at the new features and enhancements introduced in Spring 5.0.

In the next chapter, we will understand the concept of DI in detail. We will also cover the different types of configurations using DI, including performance assessment. And finally, we will go through the pitfalls of DI.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Understand common performance pitfalls and improve your application's performance
  • • Build and deploy strategies for complex applications using the microservice architecture
  • • Understand internals of JVM - the core of all Java Runtime Environments

Description

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.

Who is this book for?

If you’re a Spring developer who’d like to build high performance applications and have more control over your application's performance in production and development, this book is for you. Some familiarity with Java, Maven, and Eclipse is necessary.

What you will learn

  • • Master programming best practices and performance improvement with bean wiring
  • • Analyze the performance of various AOP implementations
  • • Explore database interactions with Spring to optimize design and configuration
  • • Solve Hibernate performance issues and traps
  • • Leverage multithreading and concurrent programming to improve application performance
  • • Gain a solid foundation in JVM performance tuning using various tools
  • • Learn the key concepts of the microservice architecture and how to monitor them
  • • Perform Spring Boot performance tuning, monitoring, and health checks

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 12, 2018
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781788830638
Vendor :
Pivotal
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Jun 12, 2018
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781788830638
Vendor :
Pivotal
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 125.97
Hands-On High Performance with Spring 5
€41.99
Software Architecture with Spring 5.0
€41.99
Mastering Spring Boot 2.0
€41.99
Total 125.97 Stars icon

Table of Contents

13 Chapters
Exploring Spring Concepts Chevron down icon Chevron up icon
Spring Best Practices and Bean Wiring Configurations Chevron down icon Chevron up icon
Tuning Aspect-Oriented Programming Chevron down icon Chevron up icon
Spring MVC Optimization Chevron down icon Chevron up icon
Understanding Spring Database Interactions Chevron down icon Chevron up icon
Hibernate Performance Tuning and Caching Chevron down icon Chevron up icon
Optimizing Spring Messaging Chevron down icon Chevron up icon
Multithreading and Concurrent Programming Chevron down icon Chevron up icon
Profiling and Logging Chevron down icon Chevron up icon
Application Performance Optimization Chevron down icon Chevron up icon
Inside JVM Chevron down icon Chevron up icon
Spring Boot Microservice Performance Tuning Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Chintan Mehta Jun 28, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very well written book !! The authors have ensured that the books addresses audiences ranging from a developer to an enterprise architect. The details have been well thought through and presented in the book. A book that all will enjoy to read and implement
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.