Home Programming Hands-On High Performance with Spring 5

Hands-On High Performance with Spring 5

By Chintan Mehta , Subhash Shah , Pritesh Shah and 2 more
books-svg-icon Book
eBook $43.99
Print $54.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99
Print $54.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Exploring Spring Concepts
About 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.
Publication date:
June 2018
Publisher
Packt
Pages
408
ISBN
9781788838382

 

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.

About the Authors
  • Chintan Mehta

    Chintan Mehta is a co-founder of KNOWARTH Technologies and heads the cloud/RIMS/DevOps team. He has rich, progressive experience in server administration of Linux, AWS Cloud, DevOps, RIMS, and on open source technologies. He is also an AWS Certified Solutions Architect. Chintan has authored MySQL 8 for Big Data, Mastering Apache Solr 7.x, MySQL 8 Administrator's Guide, and Hadoop Backup and Recovery Solutions. Also, he has reviewed Liferay Portal Performance Best Practices and Building Serverless Web Applications.

    Browse publications by this author
  • Subhash Shah

    Subhash Shah is an experienced solution architect. With 14 years of experience in software development, he works as an independent technical consultant now. He is an advocate of open source development and its utilization in solving critical business problems. His interests include Microservices architecture, Enterprise solutions, Machine Learning, Integrations and Databases. He is an admirer of quality code and test-driven development (TDD). His technical skills include translating business requirements into scalable architecture and designing sustainable solutions. He is a co-author of Hands-On High Performance with Spring 5, Hands-On AI for Banking and MySQL 8 Administrator's Guide. He has also been a technical reviewer for other books.

    Browse publications by this author
  • Pritesh Shah

    Pritesh Shah is a Solutions Architect at CentralBOS LLC. Pritesh is responsible for integrating technologies with best practices to translate business requirements into business change. He holds a degree in Computer Engineering from Dharmsinh Desai University. His expertise lies in, but is not limited to, designing, developing, deploying, and testing N-tier applications, and leading teams. He is very good at debugging problems and finding the best solution. Pritesh believes in constant improvement by quickly adapting new technologies suitable for building solutions.

    Browse publications by this author
  • Prashant Goswami

    Prashant Goswami works as a Senior Consultant at KNOWARTH Technologies and handles enterprise projects with regard to software design, development, deployment, and building processes to provide customers with affordable software solutions. He holds a master's degree in Computer Applications from Gujarat Technological University. He is able to adapt quickly to any technology and has a keen desire for constant improvement. Prashant has proven experience in working with various technologies in web application development, design patterns, enterprise architectures, and open source technologies.

    Browse publications by this author
  • Dinesh Radadiya

    Dinesh Radadiya works as a Lead Consultant and Architect at KNOWARTH Technologies, a leading open source software development company. He is a software architect with over 10 years of professional experience in developing web-based applications using various software platforms. He has proven expertise in leading and delivering software projects with varying degrees of complexity in domains such as ERP, HR, healthcare, CRM, and manufacturing. He has a keen interest in requirement analysis, progressive design, high-quality code, microservices, and refactoring.

    Browse publications by this author
Hands-On High Performance with Spring 5
Unlock this book and the full library FREE for 7 days
Start now