Mastering Spring 5.0 - Ranga Rao Karanam - E-Book

Mastering Spring 5.0 E-Book

Ranga Rao Karanam

0,0
45,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Develop cloud native applications with microservices using Spring Boot, Spring Cloud, and Spring Cloud Data Flow

About This Book

  • Explore the new features and components in Spring
  • Evolve towards micro services and cloud native applications
  • Gain powerful insights into advanced concepts of Spring and Spring Boot to develop applications more effectively
  • Understand the basics of Kotlin and use it to develop a quick service with Spring Boot

Who This Book Is For

This book is for an experienced Java developer who knows the basics of Spring, and wants to learn how to use Spring Boot to build applications and deploy them to the cloud.

What You Will Learn

  • Explore the new features in Spring Framework 5.0
  • Build microservices with Spring Boot
  • Get to know the advanced features of Spring Boot in order to effectively develop and monitor applications
  • Use Spring Cloud to deploy and manage applications on the Cloud
  • Understand Spring Data and Spring Cloud Data Flow
  • Understand the basics of reactive programming
  • Get to know the best practices when developing applications with the Spring Framework
  • Create a new project using Kotlin and implement a couple of basic services with unit and integration testing

In Detail

Spring 5.0 is due to arrive with a myriad of new and exciting features that will change the way we've used the framework so far. This book will show you this evolution—from solving the problems of testable applications to building distributed applications on the cloud.

The book begins with an insight into the new features in Spring 5.0 and shows you how to build an application using Spring MVC. You will realize how application architectures have evolved from monoliths to those built around microservices. You will then get a thorough understanding of how to build and extend microservices using Spring Boot. You will also understand how to build and deploy Cloud-Native microservices with Spring Cloud. The advanced features of Spring Boot will be illustrated through powerful examples. We will be introduced to a JVM language that's quickly gaining popularity - Kotlin. Also, we will discuss how to set up a Kotlin project in Eclipse.

By the end of the book, you will be equipped with the knowledge and best practices required to develop microservices with the Spring Framework.

Style and approach

This book follows an end-to-end tutorial approach with lots of examples and sample applications, covering the major building blocks of the Spring framework.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 450

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Spring 5.0
A comprehensive guide to becoming an expert in the Spring Framework

 

 

 

 

 

This book is based on Spring Version 5.0 RC1
Ranga Rao Karanam

 

 

 

BIRMINGHAM - MUMBAI

Mastering Spring 5.0

 

 

Copyright © 2017 Packt Publishing

 

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: June 2017

 

Production reference: 1240617

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78712-317-5

 

www.packtpub.com

Credits

AuthorRanga Rao Karanam

Copy EditorStuti Srivastava

Reviewer

Jarosław Krochmalski

Project Coordinator

Prajakta Naik

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Rekha Nair

ContentDevelopmentEditor

Siddhi Chavan

Graphics

Abhinash Sahu

Technical Editor

Supriya Thabe

Production Coordinator

Shraddha Falebhai

 

About the Author

Ranga Rao Karanam is a programmer, trainer, and architect. His areas of interest include Cloud Native Applications, microservices, evolutionary design, high-quality code, DevOps, BDD, TDD, and refactoring. He loves consulting for start-ups on developing scalable, component-based Cloud Native applications, and following modern development practices such as BDD, continuous delivery, and DevOps. He loves the freedom the Spring Framework brings to developing enterprise Java applications.

Ranga started in28minutes with the vision of creating high-quality courses on developing Cloud Native Java applications. He is looking forward to enhancing his already considerable success--75,000 students on Udemy and 35,000 subscribers on YouTube.

Ranga likes to play cricket and go hiking. His dream is to spend a year hiking the Himalayas.

 

 

My family and best friends; thank you for everything!

About the Reviewer

Jarosław Krochmalski is a passionate software designer and developer who specializes in the financial business domain. He has over 12 years of experience in software development. He is a clean-code and software craftsmanship enthusiast. He is a Certified ScrumMaster and a fan of Agile. His professional interests include new technologies in web application development, design patterns, enterprise architecture, and integration patterns. He likes to experiment with NoSQL and cloud computing. Jaroslaw has been working with IDEA since its first release and has observed the IDE grow and mature. He has been designing and developing software professionally since 2000 and has been using Java as his primary programming language since 2002. In the past, he worked for companies such as Kredyt Bank (KBC) and Bank BPS on many large-scale projects, such as international money orders, express payments, and collection systems. He currently works as a consultant for the Danish company 7N as an infrastructure architect for the Nykredit bank. You can reach him via Twitter at @jkroch or by email at [email protected].

He has authored the books, IntelliJ Idea Essentials, Developing with Docker, and Docker and Kubernetes for Java Developers by Packt, and he has reviewed another book by Packt, Spring Essentials.

 

 

Hello to all my friends in Finsys, 7N, and Nykredit-keep up the good work!

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787123170. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Evolution to Spring Framework 5.0

Spring Framework

Problems with EJB

Why is Spring Framework popular?

Simplified unit testing

Reduction in plumbing code

How does Spring Framework do this magic?

Architectural flexibility

Keep up with changing times

Spring modules

Spring Core Container

Cross-cutting concerns

Web

Business

Data

Spring Projects

Spring Boot

Spring Cloud

Spring Data

Spring Batch

Spring Security

Spring HATEOAS

New features in Spring Framework 5.0

Baseline upgrades

JDK 9 runtime compatibility

Usage of JDK 8 features in Spring Framework code

Reactive programming support

Functional web framework

Java modularity with Jigsaw

Kotlin support

Dropped features

Spring Boot 2.0 new features

Summary

Dependency Injection

Understanding dependency injection

Understanding dependencies

The Spring IoC container

Defining beans and wiring

Creating a Spring IoC container

Java configuration for the application context

A quick review

Launching the application context with Java configuration

The console log

The XML configuration for the application context

Defining the XML Spring configuration

Launching an application context with the XML configuration

Writing JUnit using the Spring context

Unit testing with mocks

Container managed beans

Dependency injection types

The setter injection

The constructor injection

Constructor versus setter injection

Spring bean scopes

Java versus XML configuration

The @Autowired annotation in depth

The @Primary annotation

The @Qualifier annotation

Other important Spring annotations

Exploring Contexts and dependency injection

An example of CDI

Summary

Building a Web Application with Spring MVC

Java web application architecture

Model 1 architecture

Model 2 architecture

Model 2 Front Controller architecture

Basic flows

Basic setup

Adding dependency for Spring MVC

Adding DispatcherServlet to web.xml

Creating Spring context

Flow 1 - Simple controller flow without View

Creating a Spring MVC controller

Running the web application

Unit testing

Setting up the Controller to test

Writing the Test method

Flow 2 - Simple controller flow with a View

Spring MVC controller

Creating a View - a JSP

View resolver

Unit testing

Setting up the Controller to test

Writing the Test method

Flow 3 - Controller redirecting to a View with Model

Spring MVC controller

Creating a View

Unit testing

Setting up the Controller to test

Writing the Test method

Flow 4 - Controller redirecting to a View with ModelAndView

Spring MVC controller

Creating a View

Unit testing

Flow 5 - Controller redirecting to a View with a form

Creating a command or form backing object

The Controller method to show the form

Creating the View with a form

Controller get method to handle form submit

Unit testing

Flow 6 - Adding validation to the previous flow

Hibernate Validator dependency

Simple validations on the bean

Custom validations

Unit testing

Controller setup

The Test method

An overview of Spring MVC

Important features

How it works

Important concepts behind Spring MVC

RequestMapping

Examples of request mapping

Example 1

Example 2

Example 3

Request Mapping methods - supported method arguments

RequestMapping methods - supported return types

View resolution

Configuring JSP view resolver

Configuring Freemarker

Handler mappings and Interceptors

Defining a HandlerInterceptor

Mapping HandlerInterceptor to handlers

Model attributes

Session attributes

Putting an attribute in the session

Reading an attribute from the session

Removing an attribute from the session

InitBinders

The @ControllerAdvice annotation

Spring MVC - advanced features

Exception handling

Common exception handling across controllers

The error view

Specific exception handling in a Controller

Internationalization

Message bundle setup

Configuring a SessionLocaleResolver

Configuring a CookieLocaleResolver

Integration testing Spring controllers

Serving static resources

Exposing static content

Caching static content

Enabling GZip compression of static content

Integrating Spring MVC with Bootstrap

Bootstrap WebJar as Maven dependency

Configure Spring MVC resource handler to deliver WebJar static content

Using Bootstrap resources in JSP

Spring Security

Adding Spring Security dependency

Configuring a filter to intercept all requests

Logout

Summary

Evolution toward Microservices and Cloud-Native Applications

Typical web application architecture with Spring

Web layer

Web application - rendering an HTML View

RESTful services

Business layer

Data layer

Integration layer

Cross-cutting concerns

Problems solved by Spring

Loose coupling and testability

Plumbing code

Lightweight architecture

Architecture flexibility

Simplified implementation of cross-cutting concerns

Design patterns for free

Application development goals

Speed

Safety

Reliability

Availability

Security

Performance

High resilience

Scalability

Challenges with monolithic applications

Long release cycles

Difficult to scale

Adapting new technologies

Adapting new methodologies

Adapting modern development practices

Understanding microservices

What is a microservice?

The microservice architecture

Microservice characteristics

Small and lightweight microservices

Interoperability with message-based communication

Capability-aligned microservices

Independently deployable units

Stateless

Automated build and release process

Event-driven architecture

Approach 1 - sequential approach

Approach 2 - event-driven approach

Independent teams

Microservice advantages

Faster time to market

Technology evolution

Availability and scaling

Team dynamics

Microservice challenges

Increased need for automation

Defining the boundaries of subsystems

Visibility and monitoring

Fault tolerance

Eventual consistency

Shared capabilities (enterprise level)

Increased need for operations teams

Cloud-Native applications

Twelve-Factor App

Maintain one code base

Dependencies

Config

Backing services

Build, release, run

Stateless

Port binding

Concurrency

Disposability

Environment parity

Logs as event streams

No distinction of admin processes

Spring projects

Spring Boot

Spring Cloud

Summary

Spring Framework

Problems with EJB

Why is Spring Framework popular?

Simplified unit testing

Reduction in plumbing code

How does Spring Framework do this magic?

Architectural flexibility

Keep up with changing times

Spring modules

Spring Core Container

Cross-cutting concerns

Web

Business

Data

Spring Projects

Spring Boot

Spring Cloud

Spring Data

Spring Batch

Spring Security

Spring HATEOAS

New features in Spring Framework 5.0

Baseline upgrades

JDK 9 runtime compatibility

Usage of JDK 8 features in Spring Framework code

Reactive programming support

Functional web framework

Java modularity with Jigsaw

Kotlin support

Dropped features

Spring Boot 2.0 new features

Summary

Building Microservices with Spring Boot

What is Spring Boot?

Building a quick prototype for a microservice

Primary goals

Nonfunctional features

Spring Boot Hello World

Configure spring-boot-starter-parent

spring-boot-starter-parent

Configure pom.xml with the required starter projects

Understanding starter projects

Configuring spring-boot-maven-plugin

Creating your first Spring Boot launch class

SpringApplication class

The @SpringBootApplication annotation

Running our Hello World application

Auto-configuration

Starter projects

What is REST?

First REST service

Simple method returning string

Unit testing

Integration testing

Simple REST method returning an object

Executing a request

Unit testing

Integration testing

Get method with path variables

Executing a request

Unit testing

Integration testing

Creating a todo resource

Request methods, operations, and URIs

Beans and services

Retrieving a Todo list

Executing the service

Unit testing

Integration testing

Retrieving details for a specific Todo

Executing the service

Unit testing

Integration testing

Adding a Todo

Postman

Executing the POST service

Unit testing

Integration testing

Spring Initializr

Creating your first Spring Initializr project

pom.xml

FirstSpringInitializrApplication.java class

FirstSpringInitializrApplicationTests class

A quick peek into auto-configuration

Summary

Extending Microservices

Exception handling

Spring Boot default exception handling

Nonexistent resource

Resource throwing an exception

Throwing a custom exception

Customizing the exception message

Response status

HATEOAS

Sending HATEOAS links in response

Spring Boot starter HATEOAS

Validation

Enabling validation on ;the controller method

Defining validations on the bean

Unit testing validations

Documenting REST services

Generating ;a Swagger specification

Swagger UI

Customizing Swagger documentation using annotations

Securing REST services with Spring Security

Adding Spring Security starter

Basic authentication

Integration testing

Unit testing

OAuth 2 authentication

High-level ;flow

Implementing OAuth 2 authentication for our service

Setting up authorization and resource servers

Executing OAuth requests

Obtaining an access token

Executing the request using the access token

Integration test

Internationalization

Caching

Spring-boot-starter-cache

Enabling caching

Caching data

JSR-107 caching annotations

Auto-detection order

Summary

Advanced Spring Boot Features

Externalised configuration

Customizing frameworks through application.properties

Logging

Embedded server configuration

Spring MVC

Spring starter security

Data Sources, JDBC and JPA

Other configuration options

Custom properties in application.properties

Configuration properties - type-safe Configuration Management

Profiles

Profiles-based Bean configuration

Other options ;for application configuration values

YAML configuration

Embedded servers

Switching to Jetty and Undertow

Building a WAR file

Developer tools

Live reload

Spring Boot Actuator

HAL Browser

Configuration properties

Environment details

Health

Mappings

Beans

Metrics

Auto-configuration

Debugging

Deploying ;an application to Cloud

Cloud Foundry

Summary

Spring Data

Background - data stores

Spring Data

Spring Data Commons

Repository

The CrudRepository interface

The PagingAndSortingRepository interface

Spring Data JPA

Spring Data JPA example

New project with Starter Data JPA

Entities

The SpringBootApplication class

Populating some data

A simple repository

Unit test

The CrudRepository interface

Unit test

The PagingAndSortingRepository interface

Unit tests

Query methods

Queries

Named Parameters

Named Query

Native query

Spring Data Rest

The GET method

The POST method

The search resource

Big Data

MongoDB

Unit test

Summary

Spring Cloud

Introducing Spring Cloud

Spring Cloud Netflix

Demo microservices setup

Microservice A

Service consumer

Ports

Centralized microservice configuration

Problem statement

Solution

Options

Spring Cloud Config

Implementing Spring Cloud Config Server

Setting up Spring Cloud Config Server

Connecting Spring Cloud Config Server to a local Git repository

Creating an environment-specific configuration

Spring Cloud Config Client

Spring Cloud Bus

The need for Spring Cloud Bus

Propogating configuration changes using Spring Cloud Bus

Implementation

Declarative REST Client - Feign

Load balancing

Ribbon

Implementation

The Name server

Limitations of hard coding microservice URLs

Workings of Name server

Options

Implementation

Setting up a Eureka Server

Registering microservices with Eureka

Connecting the service consumer microservice with Eureka

API Gateways

Implementing client-side load balancing with Zuul

Setting up a new Zuul API Gateway Server

Zuul custom filters

Invoking microservices through Zuul

Configuring service consumer to use Zuul API gateway

Distributed tracing

Distributed tracing options

Implementing Spring Cloud Sleuth and Zipkin

Integrating microservice components with Spring Cloud Sleuth

Setting up Zipkin Distributed Tracing Server

Integrating microservice components with Zipkin

Hystrix - fault tolerance

Implementation

Summary

Spring Cloud Data Flow

Message-based asynchronous communication

Complexities of asynchronous communication

Spring projects for asynchronous messages

Spring Integration

Spring Cloud Stream

Spring Cloud Data Flow

Spring Cloud Stream

Spring Cloud Stream architecture

Event processing - stock trading example

Model for stock trading example

The source application

Processor

Sink

Spring Cloud Data Flow

High-level architecture

Implementing Spring Cloud Data Flow

Setting up Spring Cloud Data Flow server

Setting up Data Flow Shell project

Configuring the apps

Configuring the stream

Deploying the stream

Log messages - setting up connections to the message factory

Log messages - the flow of events

Spring Cloud Data Flow REST APIs

Spring Cloud Task

Summary

Reactive Programming

The Reactive Manifesto

Characteristics of Reactive Systems

Reactive use case - a stock price page

The traditional approach

The reactive approach

Comparison between the traditional and reactive approaches

Reactive programming in Java

Reactive streams

Reactor

Mono

Flux

Spring Web Reactive

Creating a project using Spring Initializr

Creating a Reactive Controller

Creating an HTML view

Launching SpringReactiveExampleApplication

Reactive databases

Integrating Spring Boot Reactive MongoDB Starter

Creating a model object - a stock document

Creating a ReactiveCrudRepository

Initialising stock data using the Command Line Runner

Creating Reactive methods in Rest Controller

Updating the view to subscribe to the event stream

Launching SpringReactiveExampleApplication

Summary

Spring Best Practices

Maven standard directory layout

Layered architecture

Recommended practices

Separate API and impl for important layers

Exception handling

Spring's approach to exception handling

The recommended approach

Keeping your Spring configuration light

Using the basePackageClasses attribute in ComponentScan

Not using version numbers in schema references

Preferring constructor injection over setter injection for mandatory dependencies

Managing dependency versions for Spring Projects

Unit testing

The business layer

Web layer

The data layer

Other best practices

Integration testing

Spring Session

Example

Adding dependencies for Spring Session

Configuring Filter to replacing HttpSession with Spring Session

Enabling filtering for Tomcat by extending AbstractHttpSessionApplicationInitializer

Caching

Adding the Spring Boot Starter Cache dependency

Adding caching annotations

Logging

Logback

Log4j2

Framework independent configuration

Summary

Working with Kotlin in Spring

Kotlin

Kotlin versus Java

Variables and type inference

Variables and immutability

Type system

Functions

Arrays

Collections

No c

Data class

Creating a Kotlin project in Eclipse

Kotlin plugin

Creating a Kotlin project

Creating a Kotlin class

Running a Kotlin class

Creating a Spring Boot project using Kotlin

Dependencies and plugins

Spring Boot application class

Spring Boot application test class

Implementing a REST service using Kotlin

Simple method returning a string

Unit testing

Integration testing

Simple REST method returning an object

Executing a request

Unit testing

Integration testing

Get method with path variables

Executing a request

Unit testing

Integration testing

Summary

Preface

Spring 5.0 is due to arrive with a myriad of new and exciting features that will change the way we've used the framework so far. This book will show you this evolution--from solving the problems of testable applications to building distributed applications on the Cloud. The book begins with an insight into the new features in Spring 5.0, and shows you how to build an application using Spring MVC. You will then get a thorough understanding of how to build and extend microservices using the Spring Framework. You will also understand how to build and deploy Cloud applications. You will realize how application architectures have evolved from monoliths to those built around microservices. The advanced features of Spring Boot will also be covered and displayed through powerful examples. By the end of this book, you will be equipped with the knowledge and best practices to develop applications with the Spring Framework.

What this book covers

Chapter 1, Evolution to Spring Framework 5.0, takes you through the evolution of the Spring Framework, ranging from its initial versions to Spring 5.0. Initially, Spring was used to develop testable applications using dependency injection and core modules. Recent Spring Projects, such as Spring Boot, Spring Cloud, Spring Cloud Data Flow--deal with application infrastructure and moving applications to Cloud. We get an overview of different Spring modules and projects.

Chapter 2, Dependency Injection, dives deep into dependency injection. We will look at different kinds of dependency injection methods available in Spring, and how auto-wiring makes your life easy. We will also take a quick look into unit testing.

Chapter 3, Building a Web Application with Spring MVC, gives a quick overview of building a web application with Spring MVC.

Chapter 4, Evolution toward Microservices and Cloud-Native Applications, explains the evolution of application architectures in the last decade. We will understand why microservices and Cloud Native applications are needed and get a quick overview of the different Spring projects that help us build Cloud-Native applications.

Chapter 5, Building Microservices with Spring Boot, discusses how Spring Boot takes away the complexity in creating production-grade Spring-based applications. It makes it easy to get started with Spring-based projects and provides easy integration with third-party libraries. In this chapter, we will take the students on a journey with Spring Boot. We will start with implementing a basic web service and then move on to adding caching, exception handling, HATEOAS, and internationalization, while making use of different features from the Spring Framework.

Chapter 6, Extending Microservices, focuses on adding more advanced features to the microservices that we built in Chapter 4, Evolution toward Microservices and Cloud-Native Applications.

Chapter 7, Advanced Spring Boot Features, takes a look at the advanced features in Spring Boot. You will learn how to monitor a microservice with a Spring Boot Actuator. Then, you will deploy the microservice to Cloud. You will also learn how to develop more effectively with the developer tools provided by Spring Boot.

Chapter 8, Spring Data, discusses the Spring Data module. We will develop simple applications to integrate Spring with JPA and Big Data technologies.

Chapter 9, Spring Cloud, discusses the distributed systems in the Cloud that have common problems, configuration management, service discovery, circuit breakers, and intelligent routing. In this chapter, you will learn how Spring Cloud helps you develop solutions for these common patterns. These solutions should work well on the Cloud as well as developer local systems.

Chapter 10, Spring Cloud Data Flow, talks about the Spring Cloud Data Flow, which offers a collection of patterns and best practices for microservices-based distributed streaming and batch data pipelines. In this chapter, we will understand the basics of Spring Cloud Data Flow and use it to build basic data flow use cases.

Chapter 11, Reactive Programming, explores programming with asynchronous data streams. In this chapter, we will understand Reactive programming and take a quick look at the features provided by the Spring Framework.

Chapter 12, Spring Best Practices, helps you understand best practices in developing enterprise applications with Spring related to unit testing, integration testing, maintaining Spring configuration, and more.

Chapter 13,Working with Kotlin in Spring, introduces you to a JVM language gaining quick popularity--Kotlin. We will discuss how to setup a Kotlin project in Eclipse. We will create a new Spring Boot project using Kotlin and implement a couple of basic services with unit and integration testing.

What you need for this book

To be able to run examples from this book, you will need the following tools:

Java 8

Eclipse IDE

Postman

We will use Maven embedded into Eclipse IDE to download all the dependencies that are needed.

Who this book is for

This book is for experienced Java developers who knows the basics of Spring, and wants to learn how to use Spring Boot to build applications and deploy them to the Cloud.

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.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: "Configure spring-boot-starter-parent in your pom.xml file".

A block of code is set as follows:

<properties> <mockito.version>1.10.20</mockito.version></properties>

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

mvn clean install

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: "Provide the details and click onGenerate Project."

Warnings or important notes appear in a box like this.
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.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

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:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

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/Mastering-Spring-5.0. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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.

Evolution to Spring Framework 5.0

The first version of Spring Framework 1.0 was released in March 2004. For more than a decade and a half, Spring Framework remained the framework of choice to build Java applications.

In the relatively young and dynamic world of Java frameworks, a decade is a long time.

In this chapter, we start with understanding the core features of Spring Framework. We will look at why the Spring Framework became popular and how it adapted to remain the framework of choice. After taking a quick look at the important modules in the Spring Framework, we will jump into the world of Spring Projects. We will end the chapter by looking at the new features in Spring Framework 5.0.

This chapter will answer the following questions:

Why is Spring Framework popular?

How has Spring Framework adapted to the evolution of application architectures?

What are the important modules in Spring Framework?

Where does Spring Framework fit in the umbrella of Spring Projects?

What are the new features in Spring Framework 5.0?

Spring Framework

The Spring website (https://projects.spring.io/spring-framework/) defines Spring Framework as follows: The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications.

Spring Framework is used to wire enterprise Java applications. The main aim of Spring Framework is to take care of all the technical plumbing that is needed in order to connect the different parts of an application. This allows programmers to focus on the crux of their jobs--writing business logic.

Problems with EJB

Spring Framework was released in March 2004. When the first version of Spring Framework was released, the popular way of developing an enterprise application was using Enterprise Java Beans (EJB) 2.1.

Developing and deploying EJBs was a cumbersome process. While EJBs made the distribution of components easier, developing, unit testing, and deploying them was not easy. The initial versions of EJBs (1.0, 2.0, 2.1) had a complex Application Programmer Interface (API), leading to a perception (and truth in most applications) that the complexity introduced far outweighed the benefits:

Difficult to unit test. Actually, difficult to test outside the EJB Container.

Multiple interfaces need to be implemented with a number of unnecessary methods.

Cumbersome and tedious exception handling.

Inconvenient deployment descriptors.

Spring Framework was introduced as a lightweight framework aimed at making developing Java EE applications simpler.

Why is Spring Framework popular?

The first version of Spring Framework was released in March 2004. In the subsequent decade and a half, the use and popularity of Spring Framework only grew.

The important reasons behind the popularity of Spring Framework are as follows:

Simplified unit testing--because of dependency injection

Reduction in plumbing code

Architectural flexibility

Keeping up with changing times

Let's discuss each of these in detail.

Simplified unit testing

Earlier versions of EJBs were very difficult to unit test. In fact, it was difficult to run EJBs outside the container (as of version 2.1). The only way to test them was to deploy them in a container.

Spring Framework brought in the concept of Dependency Injection (DI). We will discuss dependency injection in complete detail in Chapter 2, Dependency Injection.

The dependency injection enables unit testing by making it easy to replace the dependencies with their mocks. We do not need to deploy the entire application to unit test it.

Simplifying unit testing has multiple benefits:

Programmers are more productive

Defects are found earlier so they are less costly to fix

Applications have automated unit tests, which can run in

Continuous Integration

builds, preventing future defects

How does Spring Framework do this magic?

In the preceding example, Spring JDBC (and Spring, in general) converts most checked exceptions into unchecked exceptions. Typically, when a query fails, there is not a lot we can do--other than to close the statement and fail the transaction. Instead of implementing exception handling in every method, we can have centralized exception handling and inject it in using Spring Aspect-Oriented Programming (AOP).

Spring JDBC removes the need to create all the plumbing code involved in getting a connection, creating a prepared statement, and so on. The jdbcTemplate class can be created in the Spring context and injected into the Data Access Object (DAO) class wherever it is needed.

Similar to the preceding example, Spring JMS, Spring AOP, and other Spring modules help in reducing a lot of plumbing code.

Spring Framework lets the programmer focus on the primary job of a programmer-- writing business logic.

Avoiding all the plumbing code also has another great benefit--reduced duplication in code. Since all code for transaction management, exception handling, and so on (typically, all your cross-cutting concerns) is implemented at one place, it is easier to maintain.

Architectural flexibility

Spring Framework is modular. It is built as a set of independent modules built on top of the core Spring modules. Most of the Spring modules are independent--you can use one of them without having to use others.

Let's look at a few examples:

In the web layer, Spring offers a framework of its own--Spring MVC. However, Spring has great support for Struts, Vaadin, JSF, or any web framework of your choice.

Spring Beans can provide lightweight implementation for your business logic. However, Spring can be integrated with EJBs as well.

In the data layer, Spring simplifies JDBC with its Spring JDBC module. However, Spring has great support for any of your preferred data layer frameworks--JPA, Hibernate (with or without JPA), or iBatis.

You have the option of implementing your cross-cutting concerns (logging, transaction management, security, and so on) with Spring AOP. Or, you can integrate with a fully fledged AOP implementation such as AspectJ.

Spring Framework does not want to be the jack-of-all-trades. While focusing on its core job of reducing coupling between different parts of the application and making them testable, Spring provides great integration with frameworks of your choice. This means you have flexibility in your architecture--if you do not want to use a specific framework, you can easily replace it with another.

Keep up with changing times

The first version of Spring Framework focused on making applications testable. However, as time moved on, there were new challenges. Spring Framework managed to evolve and stay ahead of the curve with the flexibility and modules that are offered. A couple of examples are listed as follows:

Annotations were introduced in Java 5. Spring Framework (version 2.5 – Nov 2007) was ahead of Java EE in introducing an annotation-based controller model for Spring MVC. Developers using Java EE had to wait until Java EE 6 (Dec 2009 – 2 years) before having comparable functionality.

Spring Framework introduced a number of abstractions ahead of Java EE to keep the application decoupled from specific implementation. Caching API provides a case in point. Spring provided a transparent caching support in Spring 3.1. Java EE came up with

JSR-107

for JCache (in 2014)--support for which was provided in Spring 4.1.

Another important thing Spring brings in is the umbrella of Spring Projects. Spring Framework is just one of the many projects under Spring Projects. We will discuss the different Spring Projects in a separate section. The following examples illustrate how Spring managed to stay ahead of times with new Spring Projects:

Spring Batch

defines a new approach to building Java Batch applications. We had to wait until Java EE 7 (June 2013) to have comparable batch application specification in Java EE.

As architecture evolved toward Cloud and microservices, Spring came up with new Cloud-oriented Spring Projects. Spring Cloud helps in simplifying the development and deployment of microservices. Spring Cloud Data Flow provides orchestrations around microservice applications.

Spring modules

The modularity of Spring Framework is one of the most important reasons for its widespread used. Spring Framework is highly modular with more than 20 different modules--having clearly defined boundaries.

The following figure shows different Spring modules--organized by the layer of application they are typically used in:

We will start with discussing the Spring Core Container before moving on to other modules grouped by the application layer they are typically used in.

Spring Core Container

Spring Core Container provides the core features of Spring Framework--dependency injection, IoC (Inversion of Control) container, and the application context. We will learn more about DI and IoC Container in Chapter 2, Dependency Injection.

Important core Spring modules are listed in the following table:

Module/Artifact

Use

spring-core

Utilities used by other Spring modules.

spring-beans

Support for Spring beans. In combination with spring-core provides the core feature of Spring Framework--dependency injection. Includes implementation of BeanFactory.

spring-context

Implements ApplicationContext, which extends BeanFactory and provides support to load resources and internationalization, among others.

spring-expression

Extends

EL

(

Expression Language

from JSP) and provides a language for bean property (including arrays and collections) access and manipulations.

Cross-cutting concerns

Cross-cutting concerns are applicable to all application layers--logging and security, among others. AOP is typically used to implement cross-cutting concerns.

Unit tests and integration tests fit this category since they are applicable to all layers.

Important Spring modules related to cross-cutting concerns are listed as follows:

Module/Artifact

Use

spring-aop

Provides basic support for Aspect-Oriented Programming--with method interceptors and pointcuts.

spring-aspects

Provides integration with the most popular and fully featured AOP framework, AspectJ.

spring-instrument

Provides basic instrumentation support.

spring-test

Provides basic support for unit testing and integration testing.

Web

Spring provides its own MVC framework, Spring MVC, other than providing great integration with popular web frameworks such as Struts.

Important artifacts/modules are listed as follows:

spring-web

: Provides basic web features, such as multi-part file upload. Provides support for integration with other web frameworks, such as Struts.

spring-webmvc

: Provides a fully featured web MVC framework--Spring MVC, which includes features to implement REST services as well.

We will cover Spring MVC and develop web applicaitions and rest services with it in Chapter 3, Building Web Application with Spring MVC and Chapter 5, Building Microservices with Spring Boot.

Business

The business layer is focused on executing the business logic of the applications. With Spring, business logic is typically implemented in Plain Old Java Object (POJO).

Spring Transactions (spring-tx) provides declarative transaction management for POJO and other classes.

Data

The data layer in applications typically talks to the database and/or the external interfaces. Some of the important Spring modules related to the data layer are listed in the following table:

Module/Artifact

Use

spring-jdbc

Provides abstraction around JDBC to avoid boilerplate code.

spring-orm

Provides integration with ORM frameworks and specifications-- JPA and Hibernate, among others.

spring-oxm

Provides an object to XML mapping integration. Supports frameworks such as JAXB, Castor, and so on.

spring-jms

Provides abstraction around JMS to avoid boilerplate code.

Spring Projects

While Spring Framework provides the base for core features of enterprise applications (DI, web, data), other Spring Projects explore integration and solutions to other problems in the enterprise space--deployment, Cloud, Big Data, Batch and Security, among others.

Some of the important Spring Projects are listed as follows:

Spring Boot

Spring Cloud

Spring Data

Spring Batch

Spring Security

Spring HATEOAS

Spring Boot

Some of the challenges while developing microservices and web applications are as follows:

Making framework choices and deciding compatible framework versions

Providing mechanisms for externalizing configuration--properties that can change from one environment to another

Health checks and monitoring--providing alerts if a specific part of the application is down

Deciding the deployment environment and configuring the application for it

Spring Boot solves all these problems out of the box by taking an opinionated view of how applications have to be developed.

We will look at Spring Boot in depth in two chapters--Chapter 5, Building Microservices with Spring Boot and Chapter 7, Advanced Spring Boot Features.

Spring Cloud

It is not an exaggeration to say The world is moving to the Cloud.

Cloud Native microservices and applications are the order of the day. We will discuss this in detail in Chapter 4, Evolution toward Microservices and Cloud-Native Applications.

Spring is taking rapid strides toward making application development for the Cloud simpler with Spring Cloud.

Spring Cloud provides solutions for common patterns in distributed systems. Spring Cloud enables developers to quickly create applications that implement common patterns. Some of the common patterns implemented in Spring Cloud are listed as follows:

Configuration management

Service discovery

Circuit breakers

Intelligent routing

We will discuss Spring Cloud and its varied range features in more detail in Chapter 9, Spring Cloud.

Spring Data

There are multiple sources of data in today's world--SQL (relational) and a variety of NOSQL databases. Spring Data tries to provide a consistent data-access approach to all these different kinds of databases.

Spring Data provides integration with a varied range of specifications and/or data stores:

JPA

MongoDB

Redis

Solr

Gemfire

Apache Cassandra

Some of the important features are listed as follows:

Provides abstractions around repository and object mappings--by determining queries from method names

Simple Spring integration

Integration with Spring MVC controllers

Advanced automatic auditing features--created by, created date, last changed by, and last changed date

We will discuss Spring Data in more detail in Chapter 8, Spring Data.

Spring Batch

Enterprise applications today process large volumes of data using batch programs. The needs of these applications are very similar. Spring Batch provides solutions for high- volume batch programs with high performance requirements.

Important features in Spring Batch are as follows:

The ability to start, stop, and restart jobs--including the ability to restart failed jobs from the point where they failed

The ability to process data in chunks

The ability to retry steps or to skip steps on failure

Web-based administration interface

Spring Security

Authentication is the process of identifying the user. Authorization is the process of ensuring that a user has access to perform the identified action on the resource.

Authentication and authorization are critical parts of Enterprise applications, both web applications and web services. Spring Security provides declarative authentication and authorization for Java based applications.

Important features in Spring Security are as follows:

Simplified authentication and authorization

Great integration with Spring MVC and Servlet APIs

Support to prevent common security attacks--

cross-site forgery request

(

CSRF

) and Session Fixation

Modules available for integration with SAML and LDAP

We will discuss how to secure web applications with Spring Security in Chapter 3, Building Web Application with Spring MVC.

We will discuss how to secure REST Services with Basic and OAuth authentication mechanisms using Spring Security in Chapter 6, Extending Microservices.

Spring HATEOAS

HATEOAS stands for Hypermedia as The Engine of Application State. Though it sounds complex, it is quite a simple concept. Its main aim is to decouple the server (the provider of the service) from the client (the consumer of the service).

The service provider provides the service consumer with information about what other actions can be performed on the resource.

Spring HATEOAS provides a HATEOAS implementation--especially for the REST services implemented with Spring MVC.

Important features in Spring HATEOAS are as follows:

Simplified definition of links pointing to service methods, making the links less fragile

Support for JAXB (XML-based) and JSON integration

Support for service consumer (client side)

We will discuss how to use HATEOAS in Chapter 6, Extending Microservices.

New features in Spring Framework 5.0

Spring Framework 5.0 is the first major upgrade in Spring Framework, almost four years after 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 Spring Framework 5.0 is Reactive Programming. Core reactive programming features and support for reactive endpoints are available out of the box with Spring Framework 5.0. The list of important changes includes the following:

Baseline upgrades

JDK 9 runtime compatibility

Usage of JDK 8 features in the Spring Framework code

Reactive programming support

A functional web framework

Java modularity with Jigsaw

Kotlin support

Dropped features

Baseline upgrades

Spring Framework 5.0 has JDK 8 and Java EE 7 baseline. Basically, it means that previous JDK and Java EE versions are not supported anymore.

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

Servlet 3.1

JMS 2.0

JPA 2.1

JAX-RS 2.0

Bean Validation 1.1

There are many changes to the minimum supported versions of several Java frameworks. The following list contains some of the minimum supported versions of prominent frameworks:

Hibernate 5

Jackson 2.6

EhCache 2.10

JUnit 5

Tiles 3

The following list shows the supported server versions:

Tomcat 8.5+

Jetty 9.4+

WildFly 10+

Netty 4.1+ (for web reactive programming with Spring Web Flux)

Undertow 1.4+ (for web reactive programming with Spring Web Flux)

Applications using earlier versions of any of the preceding specifications/frameworks need to be upgraded at least to the previously listed versions before they can use Spring Framework 5.0.

JDK 9 runtime compatibility

JDK 9 is expected to be released mid-2017. Spring Framework 5.0 is expected to have runtime compatibility with JDK 9.

Usage of JDK 8 features in Spring Framework code

The Spring Framework 4.x baseline version is Java SE 6. This means that it supports Java 6, 7, and 8. Having to support Java SE 6 and 7 puts constraints on the Spring Framework code. The framework code cannot use any of the new features in Java 8. So, while the rest of the world upgraded to Java 8, the code in Spring Framework (at least the major parts) was restricted to using earlier versions of Java.

With Spring Framework 5.0, the baseline version is Java 8. Spring Framework code is now upgraded to use the new features in Java 8. This will result in more readable and performant framework code. Some of the Java 8 features used are as follows:

Java 8 default methods in core Spring interfaces

Internal code improvements based on Java 8 reflection enhancements

Use of functional programming in the framework code--lambdas and streams

Reactive programming support

Reactive programming is one of the most important features of Spring Framework 5.0.

Microservices architectures are typically built around event-based communication. Applications are built to react to events (or messages).

Reactive programming provides an alternate style of programming focused on building applications that react to events.

While Java 8 does not have built-in suppport 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.

We will discuss Reactive Programming and how you can implement it with Spring Web Flux in Chapter 11, Reactive Programming.

Java modularity with Jigsaw

Until Java 8, the Java platform was not modular. A couple of important problems resulted out of this:

Platform Bloat

: Java modularity has not been a cause of concern in the last couple of decades. However, with

Internet of Things

(

IOT

) and new lightweight platforms such as Node.js, there is an urgent need to address the bloat of the Java platform. (Initial versions of JDK were less than 10 MB in size. Recent versions of JDK need more than 200 MB.)

JAR Hell

: Another important concern is the problem of JAR Hell. When Java ClassLoader finds a class, it will not see whether there are other definitions for the class available. It immediately loads the first class that is found. If two different parts of the application need the same class from different jars, there is no way for them to specify the jar from which the class has to be loaded.

Open System Gateway initiative (OSGi) is one of the initiatives, started way back in 1999, to bring modularity into Java applications.

Each module (referred to as bundle) defines the following:

imports

: Other bundles that the module uses

exports

: Packages that this bundle exports

Each module can have its own life cycle. It can be installed, started, and stopped on its own.

Jigsaw is an initiative under Java Community Process (JCP), started with Java 7, to bring modularity into Java. It has two main aims:

Defining and implementing a modular structure for JDK

Defining a module system for applications built on the Java platform

Jigsaw is expected to be part of Java 9 and Spring Framework 5.0 is expected to include basic support for Jigsaw modules.