Book Image

Spring 5.0 Cookbook

By : Sherwin John C. Tragura
Book Image

Spring 5.0 Cookbook

By: Sherwin John C. Tragura

Overview of this book

The Spring framework has been the go-to framework for Java developers for quite some time. It enhances modularity, provides more readable code, and enables the developer to focus on developing the application while the underlying framework takes care of transaction APIs, remote APIs, JMX APIs, and JMS APIs. The upcoming version of the Spring Framework has a lot to offer, above and beyond the platform upgrade to Java 9, and this book will show you all you need to know to overcome common to advanced problems you might face. Each recipe will showcase some old and new issues and solutions, right from configuring Spring 5.0 container to testing its components. Most importantly, the book will highlight concurrent processes, asynchronous MVC and reactive programming using Reactor Core APIs. Aside from the core components, this book will also include integration of third-party technologies that are mostly needed in building enterprise applications. By the end of the book, the reader will not only be well versed with the essential concepts of Spring, but will also have mastered its latest features in a solution-oriented manner.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

A cookbook is a definitive reference material that consists of several essential recipes on computer programming used for academic, professional, or personal workshops. This book is a large reference database of programming concepts, which aims to describe, highlight, and identify the general features of Spring Framework 5 and also its distinctive features and characteristics as the newest installment of Spring platforms.

The book is written for users who wants to build Spring 5 applications using its core Maven dependencies and for those who prefer to use Spring Boot as the mechanism for web development. It is divided into disciplines that are considered strengths of Spring 5 in which some are familiar concepts such as bean scopes, Model-View-Controller, aspect-object programming, @Async transactions, and Spring security concepts. There are also new theoretical frameworks that can only be found in this Spring version such as Reactor Core, WebFlux, cold and hot streams, and reactive web programming.

You will be guided on how to install the appropriate tools and plug-ins for Spring 5 to work properly. For those who are new to Spring framework, you will also be given a short discussion on its core principles through recipes that handle Dependency Injection and Inversion of Control and implementation of the ApplicationContext container. For experts, this book offers some recipes that illustrate how to implement reactive components such as reactive JPA, service layers, message-driven transactions, and WebSocket implementation.

When it comes to difficulty levels, there are parts that are for beginners and enthusiasts who want to learn Spring web development. But most chapters are intended for experienced Spring users who want to learn functional and reactive programming components of this newest Spring installment. This will provide a new paradigm to those who are seeking optimal and faster software performance with the help of the Stream API, Publisher<T>, Flux<T>, @Async, Callable<T>, and HandlerFunction<T>. These are just few concepts that this book will emphasize and expound through some robust and practical set of recipes.

What this book covers

Chapter 1, Getting Started with Spring, is the installation and configuration section of the book. It consists of recipes that enumerate the steps on how to install Java 1.8, Tomcat 9 with TLS, Eclipse STS 8.3, MySQL 5.7, and MongoDB 3.2. This will also provide a procedure on how to build a Maven project with Spring 5 dependencies and deploy it using the Tomcat Maven plugin.

Chapter 2, Learning Dependency Injection (DI), covers the core concepts of Inversion of Control (IoC) design pattern. This chapter provides recipes on how to build ApplicationContext through XML-based configurations and the JavaConfig specification. You will also be guided on how to perform a @Bean injection and autowiring. Most importantly, this chapter will highlight the role of IoC in building Spring MVC web applications.

Chapter 3, Implementing MVC Design Pattern, highlights the construction of Spring 5 web applications based on its Spring WebMvc module. This will provide recipes that aim to implement the controller, service, and DAO layers with some supporting features such as view resolvers, message bundles, and JDBC connectivity.

Chapter 4, Securing Spring MVC Application, is all about Spring Security integration with Spring 5. The chapters that use Spring MVC will be applying Spring Security 4, while those that implement th Spring WebFlux module will be using Spring Security 5 with asynchronous and reactive transactions. Advance topics such as protection against Cross-Site Request Forgery (CSRF), session fixation, and cross-site scripting (XSS) and Clickjacking will also be covered in some recipes.

Chapter 5, Cross-Cutting the MVC, contains recipes that discuss implement aspects, advices, and pointcuts. The aspect-object programming paradigm will be thoroughly discussed, focusing on how it will be used across the Spring 5 platform. Concepts such as improvised security, validating method parameters, monitoring @Controller request transactions, and interception will also be included in the recipes.

Chapter 6, Functional Programming, contains recipes that will layout the foundation of functional programming paradigm in Spring 5. This will showcase the Stream API of Java 1.8 and its threaded operations being applied to the service layer of the platform. Topics such as sequential and parallel streams will be covered here.

Chapter 7, Reactive Programming, focuses on Spring 5 integration with the Reactor Core module. The recipes of this chapter will apply Publisher<T> and Subscriber<T> from the reactive stream specification in order to generate reactive data streams with short-lived and continuous stream flows. Also included are implementations of asynchronous transactions using @Async, Callable<T>, and DeferredResult<T>. Apart from Reactor Core, this chapter will also include other reactive libraries such as RxJava 2.0 used in building the reactive service layer of Spring 5.

Chapter 8, Reactive Web Applications, is where we start using Reactor Core in building reactive web applications. This includes recipes that use Publisher<T>, Flux<T>, and Mono<T> in building the service and the @Controller layer. Some recipes also discuss how to implement Callable<T> and DeferredResult<T> response transactions. In this chapter, some view resolvers will be introduced to recognize reactive streams.

Chapter 9, Spring Boot 2.0, discusses how to build and deploy Spring MVC and Spring WebFlux projects using Spring Boot 2.0. It is only in this chapter that the functional and reactive web framework of Spring 5 will be completely implemented using the HandlerFunction<T> and RouterFunction<T> reactive components executed by the Reactor Netty server.

Chapter 10, The Microservices, applies the concept of functional and reactive web framework to microservices. This provides a set of recipes that will showcase the strength of Spring Boot 2.0 in building and consuming synchronous, asynchronous, and reactive services in a microservice. In the chapter, we will cover the procedure to implement a loosely-coupled microservices setup through the Eureka server or Docker.

Chapter 11, Batch and Message-Driven Processes, talks about how to implement a totally loosely-coupled microservices through message-driven transactions. There are also recipes that will discuss on how to implement background batch processes using Spring Batch and Spring Cloud Task.

Chapter 12, Other Spring 5 Features, is one of the most important chapters in this book because it showcases other reactive and non-reactive components of Spring 5 that are not mentioned in the previous chapter but are useful to professionals. In this chapter, there are recipes dedicated to how to enable Hibernate 5, WebSocket, and HazelCast caching. Also, there are others written to showcase the reactive features of Spring 5 such as Spring Data JPA, Spring Data MongoDB, and Kotlin.

Chapter 13, Testing Spring 5 Components, highlights the Spring TestContext framework and how it is utilized in testing synchronous, asynchronous, and reactive Spring components such as native and REST services, repositories, JPA transactions, controllers, and views.

What you need for this book

Firstly, this book is intended for readers who have a background at least in Java SDK programming. This book does not cover anything about how to start dealing with Java as a language. Secondly, each chapter contains recipes that can be developed using STS Eclipse 3.8 and can be executed using Apache Tomcat 9.x and the Reactor Netty server. The following are the required tools and libraries needed to perform the recipes in this book:

  • Any machine with at least 4 GB of RAM
  • Java 1.8
  • STS Eclipse 3.8
  • Apache Tomcat 9.x
  • OpenSSL for Windows
  • MySQL 5.7
  • MongoDB 3.2
  • RabbitMQ 3.6
  • Erlang 9.0
  • Apache Couchdb 2.1.0
  • Docker Toolbox for Windows
  • Google Chrome or Mozilla Firefox browser

Other versions of these requirements will not be covered in this book.

Who this book is for

This book is composed of two menus: core concepts and advance concepts. The core concepts found in the recipes of chapters 1 to 3 are recommended to Java programmers who have no background in Spring Framework but are willing to start their career with the Spring 5 platform. Also, enthusiasts who know OOP and MVC concepts can also deal with the first three chapters since these are just the same ideas and principles being implemented in Spring 4 and below.

The recipes covered in chapters 4 to 13 are for experienced Spring developers who want to learn how to integrate modules such as Spring Security, Spring WebFlux, Reactor Core, Spring Batch, Spring Cloud, and advance related libraries. Aspects, advices, pointcuts, and interceptors, for instance, can only be understood by readers who know where in the Spring platform to apply the cross-cutting procedure. It also takes a deep knowledge of Spring when it comes to implementing REST web services and how to consume them using client APIs. Since this book is more inclined to asynchronous and reactive programming concepts, this book will be challenging for someone who knows Spring Framework very well.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

All recipes codes are written inside a numbered bullet and follow the following style:

public Set<String> getDistinctNames(){
    Function<Employee,String> allNames = (e) -> e.getFirstName();
    Set<String> setNames = employeeDaoImpl.getEmployees()
    .stream()
    .filter((a) -> a.getAge() > 25)
    .map(allNames)
    .collect(Collectors.toCollection(HashSet::new));
    return setNames;
}

Code words in text, HTML tags, database table names, folder names, filenames, file extensions, and pathnames are shown as follows: "Import socketapps.js inside hotline.html using the <script> tag"

A URL is written as follows: "Visit the site https://www.mongodb.com/download-center#community to download MongoDB under different operating system platforms. It also comes with SSL and no-SSL support."

Acronyms and module names may be shown in bold: "The Hibernate 5 has no dedicated starter POM in Spring Boot 2.0, but it is by default contained in the Spring Data JPA starter POM."

Any command-line input or output is written as follows:

keytool -import -alias spring5server -file spring5packt.crt -keystore "<Java1.8_folder>\Java1.8.112\jre\lib\security\cacerts" -storepass changeit

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "On the dashboard, look for IDE EXTENSIONS and click that button".

Important phrases, terminology, ideas, and concepts are written in this style: "MongoDB is an unstructured database so it has no concept of relational models such as database and table schema".

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Spring-5.0-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Spring5Cookbook.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.