34,79 €
Build scalable and flexible Rest APIs and microservices using the latest versions of Spring and Spring Boot
Spring 5.1 is the latest release of the widely used Spring Framework. This book takes you through the evolution of building enterprise-ready applications with Spring and Spring Boot.
Mastering Spring 5 starts with an overview of some of the important Spring Framework features relating to aspect-oriented programming, task scheduling, and scripting with the help of practical examples. You'll learn about the standard dependency injection specification for Java contexts and CDI and how the Spring Framework supports it. You’ll gain an understanding of how application architectures have evolved from monoliths to microservices and be able to build your own microservices using Spring Boot. Complete with real-world examples, this book will help you gain powerful insights into Spring Boot 2.1 and learn how to develop cloud-native microservices with Spring Cloud. You’ll even explore how to secure a REST API with Spring Security and get started with your first full stack application using React. Furthermore, you’ll get to grips with Kotlin fundamentals and build a Kotlin project in Eclipse.
By the end of this book, you’ll be equipped with all the knowledge required to develop microservices and full stack applications with the Spring Framework.
This book is for experienced Java and enterprise Java developers and programmers who have a basic understanding of the Spring Framework.
Ranga Rao Karanam is the founder of in28Minutes, a company that trains 300,000 developers across the globe in relation to the cloud, microservices, Spring, Spring Boot, and Containers. He loves programming, and loves consulting for start-ups on developing scalable cloud applications and following modern development practices, such as BDD, continuous delivery, and DevOps. In his spare time, he loves hiking, cricket, and tennis. His ambition is to spend a year hiking the Himalayas.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 529
Veröffentlichungsjahr: 2019
Copyright © 2019 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Tiksha SarangSenior Editor: Afshaan KhanTechnical Editor: Royce JohnCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Rekha NairProduction Designer: Arvindkumar Gupta
First published: June 2017 Second edition: July 2019
Production reference: 1100719
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-569-2
www.packtpub.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
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.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.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.
Ranga Rao Karanam is the founder of in28Minutes, a company that trains 300,000 developers across the globe in relation to the cloud, microservices, Spring, Spring Boot, and Containers. He loves programming, and loves consulting for start-ups on developing scalable cloud applications and following modern development practices, such as BDD, continuous delivery, and DevOps.
In his spare time, he loves hiking, cricket, and tennis. His ambition is to spend a year hiking the Himalayas.
Sherwin John Calleja Tragura is currently a Java-JakartaEE-C# corporate trainer who is also a subject matter expert on Python 3, Angular 7, Ionic 3, Alfresco, CMS, DMS, and Webscripts. He is currently involved in business analysis and the technical design of a web and mobile project with a number of ongoing projects in the area of reactive programming and web frameworks. He graduated from the University of the Philippines Los Baños, where he started his career as a university lecturer. He has authored Spring 5 Cookbook, Spring MVC Blueprints, and Jakarta EE 8 Recipes, all published by Packt Publishing. He is continuing to explore and share new techniques in the areas of microservices, Java, C# .NET, and JavaScript frameworks, all of which will prove useful to future projects and training.
Samer Abdelkafi has over 14 years' experience as a software architect and engineer, with a primary focus on open source technologies. He has contributed to numerous projects in different sectors, including banking, insurance, education, public services, and utility billing. At the end of 2016, he created DEVACT, a company specializing in information technology consultancy.
In addition to his day job, he has reviewed many books related to Spring projects, including Mastering Spring Cloud, Mastering Spring Boot 2.0, and Spring MVC Blueprints.
Mohamed Sanaulla is a full-stack developer with more than 8 years' experience in developing enterprise applications and Java-based backend solutions for e-commerce applications. His interests include enterprise software development, refactoring and redesigning applications, designing and implementing RESTful web services, troubleshooting Java applications for performance issues, and TDD.
He has significant expertise in Java-based application development, ADF (a JSF-based Java EE web framework), SQL, PL/SQL, JUnit, designing RESTful services, Spring, Spring Boot, Struts, Elasticsearch, and MongoDB. He is also a Sun Certified Java Programmer for the Java 6 platform. He is a moderator for JavaRanch, and likes to share his findings on his blog.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering Spring 5 Second Edition
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Section 1: Getting Started with Spring and Spring Boot
Spring Landscape - Framework, Modules, and Projects
Exploring Spring and its evolution
Beginning with the first version of the Spring Framework
Loose coupling and testability
Architectural flexibility
Reduction in plumbing code
Learning about the early years of the Spring Framework – Spring Projects
Staying ahead of Java EE
Evolution toward microservices – Spring Boot and Spring Cloud
Building microservices quickly with Spring Boot
Connecting microservices with the cloud using Spring Cloud
Quickly revising what we learned
Learning about Spring Modules
Spring Core Container
Cross-cutting concerns
Web – Spring MVC
The business layer
The data layer
Beginning with Spring Projects
Spring Boot
Spring Cloud
Spring Data
Beginning with Spring Batch
Spring Security
Spring HATEOAS
New features in Spring Framework 5.0 and 5.1
Baseline upgrades
Java 11 Support
Usage of JDK 8 features in the Spring Framework code
Reactive programming support
Functional web framework
Java modularity with Jigsaw
Kotlin support
Dropped features
Learning about new features in Spring Boot 2.0 and 2.1 
Summary
Further reading
Dependency Injection and Unit Testing
Technical requirements
Understanding a dependency
Why do we have dependencies?
What is DI?
Loose and tight coupling
Eliminating tight coupling and making code loosely coupled
Creating an interface for DataServiceImpl
Moving creation of a dependency outside BusinessServiceImpl
Creating an interface for BusinessServiceImpl
Understanding terminology – beans, wiring, and DI
What does the Spring Framework do?
Question 1 – how does Spring IoC container know which beans to create?
Question 2 – how does the Spring IoC container know the dependencies of the bean?
Launching a Spring IoC container
Creating a Java configuration for the application context
Launching a Java configuration
Defining a component scan
Running the application context
What's happening in the background?
Understanding the Spring Framework in depth
Container Managed Beans
Java versus XML configuration
Using XML configuration for the application context
Defining the XML Spring configuration
Launching an application context with the XML configuration
The @Autowired annotation in depth
The @Primary annotation
The @Qualifier annotation
Understanding DI options
The setter injection
The constructor injection
Constructor versus setter injection
Customizing Spring beans – scope
Other important Spring annotations
Exploring CDI
An example of CDI
Unit testing the Spring application context
What is unit testing?
Writing JUnit using the Spring context
Unit testing with mocks
Summary
Further reading
Building Web Applications with Spring MVC
Technical requirements
Understanding the architectures of Java servlet web applications
Model 1 architecture
Model 2 architecture
Model 2 FrontController architecture
Learning Spring MVC with six basic flow examples
Setting up a Spring MVC application
Adding dependency for Spring MVC
Adding DispatcherServlet to web.xml
Creating a Spring context
Flow 1 – simple controller flow without View
Creating a Spring MVC controller
Running the web application
Flow 2 – creating a simple controller flow with a View – JSP
Creating a Spring MVC controller
Creating a View – a JSP
Configuring a View resolver
Flow 3 – controller redirecting to a View with a model
Spring MVC controller
Creating a View
Flow 4 – controller redirecting to a View with ModelAndView
Spring MVC controller
Creating a View
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
Flow 6 – adding validation to the previous flow
Adding the Hibernate Validator dependency
Defining simple validations on the bean
Implementing custom validations
An overview of Spring MVC
Understanding the important features
Working with Spring MVC
Important concepts behind Spring MVC
RequestMapping
Examples of request mapping
Example 1
Example 2
Example 3
RequestMapping methods – supported method arguments
RequestMapping methods – supported return types
Exploring View resolution
Configuring the JSP View resolver
Configuring Freemarker
Exploring handler mappings and interceptors
Defining a HandlerInterceptor
Mapping HandlerInterceptor to handlers
Using model attributes
Using session attributes
Putting an attribute in the session
Reading an attribute from the session
Removing an attribute from the session
Understand the need for InitBinders
Implementing common features using the @ControllerAdvice annotation
A quick look at Spring MVC advanced features
Implementing exception handling
Common exception handling across controllers
Defining the error View
Creating specific exception handling in a Controller
Internationalizing your application
Setting up the message bundle 
Configuring SessionLocaleResolver
Configuring CookieLocaleResolver
Serving static resources
Exposing static content
Caching static content
Enabling gzip compression of static content
Integrating Spring MVC with Bootstrap
Defining Bootstrap WebJar as a Maven dependency
Configuring the Spring MVC resource handler to deliver WebJar static content
Using Bootstrap resources in JSP
Unit testing Spring MVC applications – basic flows
Flow 1 – simple controller flow without View
Setting up the controller to test
Writing the Test method
Flow 2 – simple controller flow with a View
Setting up the controller to test
Writing the Test method
Flow 3 – controller redirecting to a View with Model
Setting up the controller to test
Writing the Test method
Flow 4 – controller redirecting to a View with ModelAndView
Flow 5 – controller redirecting to a View with a form
Flow 6 – adding validation to the previous flow
Controller setup
The Test method
Writing integration tests for Spring MVC controllers
Spring Security
Adding the Spring Security dependency
Configuring a filter to intercept all requests
Logout
Summary
Further reading
Getting Started with Spring Boot
Technical requirements
What is Spring Boot?
Steps involved in building a quick prototype for an application
Primary goals of Spring Boot
Understanding Spring Boot's non-functional features
Building a Hello World application with Spring Boot
Creating pom.xml with spring-boot-starter-parent
Understanding spring-boot-starter-parent
Configuring pom.xml with starter projects
Understanding starter projects
Configuring spring-boot-maven-plugin
Creating your first Spring Boot launch class
Understanding the SpringApplication class
Requirements for the @SpringBootApplication annotation
Running our Hello World application
Understanding the magic of AutoConfiguration
Exploring Spring Boot starter projects
Getting started with SPRING INITIALIZR
Creating your first SPRING INITIALIZR project
Exploring pom.xml
Understanding the FirstSpringInitializrApplication.java class
Looking at the tests – the FirstSpringInitializrApplicationTests class
A quick peek into AutoConfiguration
Externalizing application configuration
Getting started with application.properties
Customizing frameworks through application.properties
Configuring logging
Customizing the embedded server configuration
Configuring Spring MVC
Configuring Spring starter security
Customizing data sources, JDBC, and JPA
Looking at other configuration options
Defining application-specific, custom-defined properties
Providing type-safe configuration through configuration properties 
Creating profiles for different environments
Configuring dynamic beans based on active profiles
Other options for providing application configuration
Exploring the YAML configuration
Understanding embedded servers
Understanding traditional Java application deployment
Understanding embedded servers
Switching to Jetty and Undertow embedded servers
Building a traditional WAR file instead of using a JAR
Using developer tools to improve productivity
Enabling live reload on a browser
Using Spring Boot Actuator for application monitoring
Using the HAL browser to browse actuator endpoints
Looking at application configuration
Getting environment details
Monitoring application health
Getting mapping information
Debugging with the bean configuration
Exploring important metrics
Getting debug information about AutoConfiguration
Debugging
Summary
Digging Deeper into the Spring Framework
Technical requirements
Exploring AOP with Spring and AspectJ
Exploring cross-cutting concerns and AOP
Understanding important AOP terminology
Understanding weaving
AOP frameworks
Getting hands-on with AOP
Setting up a simple business scenario
Identifying the PointCut
Defining the aspect
Understanding @After advice
Understanding @AfterReturning advice
Understanding @Around advice
PointCut best practices
Defining custom AOP annotations
Scheduling tasks with Spring
Scheduling tasks with @Scheduled
Running tasks asynchronously using @Async
Returning values from @Async methods
Understanding task executors
Scripting with the Spring Framework
JSR 223 – scripting for the JavaTM platform
Executing JavaScript code in Java
Executing Groovy code in Java
Executing Groovy code in Spring enterprise applications
Inlining Groovy code into Spring context XML
Summary
Section 2: Building a REST API and Full Stack Applications with Spring
Building REST APIs with Spring Boot
Understanding REST
Designing your first REST API
Deciding on request methods and URIs for REST API operations
Understanding the high-level approach for creating APIs
Creating a Hello World API with Spring Boot
Creating an API that returns a Hello World string
Creating a REST API that returns a welcome JSON response
Executing a request
Creating a welcome message with a name path variable
Executing a request
Creating a todo REST API
Setting up beans and services
Retrieving a todo list
Executing the service
Retrieving details for a specific Todo
Executing the service
Adding a Todo
Introducing Postman – a REST API client
Executing the POST service using Postman
Updating a Todo
Executing the PUT service using Postman
Deleting a Todo
Executing the DELETE service using Postman
Implementing exception handling for REST APIs
Understanding Spring Boot default exception handling
What happens when a resource doesn't exist?
What happens when service code throws a runtime exception?
What happens when the service method throws a custom exception?
Customizing the exception response
Defining the exception response structure
Defining custom exception handling advice for TodoNotFoundException
Defining global default exception handling advice for all other exceptions
Mapping response statuses for different scenarios
Exploring HATEOAS
Sending HATEOAS links in response
Spring Boot starter HATEOAS
Implementing validation for REST APIs
Enabling validation on the controller method
Defining validations on the bean
Documenting REST services using the OpenAPI Specification
Generating a Swagger specification
Exploring the Swagger specification
Using the Swagger UI to navigate the Swagger documentation
Customizing the Swagger documentation using annotations
Implementing internationalization for REST APIs
Implementing caching for REST APIs
Exploring a starter project for caching – spring-boot-starter-cache
Enabling caching on the application
Caching data
JSR-107 caching annotations
Understanding the auto-detection order of caching providers
Deploying Spring Boot applications to the cloud
Deploying applications to Cloud Foundry
Summary
Unit Testing REST API with Spring Boot
Technical requirements
Unit testing REST API with Spring Boot
Adding dependency on Spring Boot Starter Test
Unit tests for the BasicController API
Setting up the basic unit test
Writing a unit test for the Hello World API returning a string
Writing a unit test for the Hello World API returning a JSON
Writing a unit test for the Hello World API with a path parameter
Unit tests for the TodoController API
Setting up unit tests for the TodoController API
Writing a unit test to retrieve all todos – the GET method
Writing a unit test for retrieving a specific todo – the GET method
Writing a unit test for creating a todo – the POST method
Writing a unit test for creating a todo with validation errors
Writing a unit test for updating a todo – the PUT method
Writing a unit test for deleting a todo – the DELETE method
Integration testing REST API with Spring Boot
Writing integration tests for BasicController
Writing an integration test for the Hello World API returning a string
Writing an integration test for the Hello World API returning a JSON
Writing an integration test for the Hello World API with a path parameter
Integration tests for the TodoController API
Todo API integration testing setup
Writing an integration test to retrieve all todos – the GET method
Writing an integration test for creating a todo – the POST method
Writing an integration test for updating a todo – the PUT method
Writing an integration test for deleting a todo – the DELETE method
Unit and integration testing best practices
Summary
Further reading
Securing REST API with Spring Security
Technical requirements
Security REST API with Spring Security
Securing the REST API basics
Authentication
Authorization
Implementing security for REST API
Adding Spring Security to the Todo API
Adding Spring Security Starter
Spring Boot Starter security dependencies
Spring Boot Starter security auto-configuration
Updating an integration test with basic authentication credentials
Updating a unit test to disable security
A quick review of the chapter until now
Understanding Spring Security
Reviewing the log
Understanding Spring Security filters
Understanding authentication in Spring Security
Understanding authentication managers
Understanding provider managers
Understanding authentication providers
Implementing the UserDetailsService
Managing users with a UserDetailsManager
Understanding authentication extension points in Spring Security
Providing a custom implementation of the Use DetailsService
Extending the web security configurer adapter to configure a global authentication manager
Using the web security configurer adapter to configure web security
Understanding authorization in Spring Security
Using access decision manager to support authorization
Understanding authentication extension points in Spring Security
Using the web security configurer adapter to configure HTTP security
Providing secured annotations on service methods
Providing JSR-250 annotations on service methods
Using Spring Security pre and post annotations
Implementing security best practices with Spring Security
Exploring OAuth2 authentication
Understanding OAuth2 high-level flow
Exploring Authorization Grant Flow
Resource Access Flow
Creating the OAuth2 Server
Setting up the authorization server
Configuring the user credentials for REST API
Configuring the authorization server with third-party client credentials
Obtaining an access token
Setting up the resource server
Executing the request using the access token
Updating the integration test
Authentication with JWT
Introducing JWT
JWT payload
JOSE header
JWT signing and token creation
Using JWT for REST API authentication
Using JWT with OAuth2
Summary
Further reading
Full Stack App with React and Spring Boot
Technical requirements
Understanding full stack architecture
Understanding the need for full stack architecture
Introducing React
Components of a frontend application
JSX
Combining JSX and components
Creating a Header component
Creating a Footer component
Creating a Todo component
Building your first React application
Using create-react-app
Importing a React application into Visual Studio Code IDE
Quick introduction to the folder structure
Initializing the React framework 
Creating a Todo component
Adding basic Todo management features
Validations
Loading Todos from the API with the axios framework
Adding todos invoking the RESTful API
Authentication
Basic authentication
JWT token-based authentication
Summary
Further reading
Managing Data with Spring Data
Technical requirements
Challenges with a variety of data stores
Communicating with relational databases
Introducing Spring Data
Understanding Spring Data Commons
Exploring the Repository interface
Exploring the CrudRepository interface
Exploring the PagingAndSortingRepository interface
Connecting to relational databases using Spring Data JPA
Understanding Spring Data JPA with an example
Create a new project with a starter data JPA
Defining entities
Creating the SpringBootApplication class
Populating some data
Creating a simple repository
Creating a unit test
Create a repository extending the CrudRepository interface
Testing using a unit test
Creating a repository extending the PagingAndSortingRepository interface
Exploring using unit tests
Writing custom query methods
Writing custom JPQL queries
Using named parameters
Using named queries
Executing native SQL queries
Getting started with transaction management
Understanding the Spring @Transactional annotation
Understanding Spring Boot auto-configuration for transactions
Interacting with MongoDB using Spring Data
Setting up the dependencies
Creating a Person entity
Creating a Person repository
Testing the repository in a unit test
Using Spring Data REST to create REST APIs
Exploring the GET method
Exploring the POST method
Using the search resource
Summary
Section 3: Cloud, Microservices, and Best Practices with Spring
Getting Started with Microservices
Understanding the goals of application development
Developing applications quickly – speed
Building dependable applications – safety
Reliability – does the application behave as expected?
Availability – is your application available all the time?
Security – is your application secure?
Performance – is your application quick enough?
High resilience – does your application react well to failures?
Scalability – what is needed to support a drastic increase in application load?
Challenges with monolithic applications
Challenges in releasing updates – long release cycles
Difficulties with scaling up
Difficulties with adapting new technologies
Difficulties with adapting new methodologies
Challenges in adapting modern development practices
Getting started with microservices
What is a microservice?
Understanding the big idea of microservice architecture
Understanding microservice characteristics
Small and lightweight microservices
Interoperability with message-based communication
Capability-aligned microservices
Independently deployable microservices
Stateless microservices
Completely automated build and release process
Adherence to event-driven architectures
Approach 1 – The sequential approach
Approach 2 –  The event-driven approach
Independent teams developing and supporting microservices – DevOps
Understanding the advantages of microservice architectures
Faster time to market
Quick adaptation to technology evolution
Ability to easily scale
Compatibility with current development methodologies
Exploring microservice challenges
Increased need for automation
Challenges in defining the boundaries of subsystems
Increased need for visibility and monitoring
Increased need for fault tolerance
Maintaining consistency across microservices
Establishing standardized shared capabilities (enterprise level)
Increased need for operations teams
Understanding cloud-native applications
What is the Twelve-Factor App?
Maintain one code base
Explicit declaration of dependencies
Application configuration stored in an environment
All dependencies are treated as backing services
Clear separation between build, release, and run phases
Applications do not store states – stateless
All the services are exposed with port binding
Possibility to scale horizontally – concurrency
Each application instance is disposable
Achieving environmental parity – all environments are the same
Treating all logs as event streams
No distinction for admin processes
Exploring Spring projects for microservices
Getting an overview of Spring Boot
Getting started with Spring Cloud
Exploring Spring Cloud Netflix
Summary
Further reading
Building Microservices with Spring Boot and Spring Cloud
Technical requirements
Understanding the microservices we will build
Setting up Microservice A
Step 1 – initializing Microservice A using SPRING INITIALIZR
Step 2 – creating the random list service in Microservice A
Building the Service Consumer microservice
Creating the method to consume the random list service (from Microservice A)
Testing the Service Consumer microservice
Standardizing ports that are used for different microservices
Using recommended versions for Spring Boot and Spring Cloud
Exploring centralized microservice configuration
Problem statement
Solution
Options
Spring Cloud Config
Implementing Spring Cloud Config Server
Setting up Spring Cloud Config Server
Creating a service in Microservice A to return a message from the application configuration
Connecting Spring Cloud Config Server to a local Git repository
Creating a development environment-specific configuration for Microservice A
Enhancing Microservice A to make it a Spring Cloud Config Client
Getting an overview of event-driven approaches
Understanding Spring JMS using the JMS API
AMQP 
Getting started with Spring Cloud Bus
The need for Spring Cloud Bus
Propagating configuration changes using Spring Cloud Bus
Implementing Spring Cloud Bus 
Declarative REST client – Feign
Implementing load balancing for microservices
Ribbon for client-side load balancing
Implementing Ribbon in the Service Consumer microservice
Understanding the need for a naming server
Limitations of hardcoding microservice URLs
The working of a naming server
Naming server options supported by Spring Cloud
Implementing the Eureka naming service
Setting up Eureka Server
Registering microservices with Eureka
Connecting the Service Consumer microservice with Eureka
Understanding API gateways
Implementing API gateway with Zuul
Setting up a new Zuul API gateway server
Configuring Zuul custom filters for logging every request
Invoking microservices through Zuul
Configuring Service Consumer to use the Zuul API gateway
Understanding distributed tracing
Implementing Spring Cloud Sleuth and Zipkin
Integrating microservice components with Spring Cloud Sleuth
Setting up a Zipkin distributed tracing server
Integrating microservice components with Zipkin
Implementing fault tolerance with Hystrix
Integrating Hystrix into the Service Consumer microservice
Summary
Further reading
Reactive Programming
Technical requirements
The reactive manifesto
Characteristics of reactive systems
Reactive use case – a stock price page
A quick look at the traditional approach 
How is the reactive approach different?
Comparing traditional and reactive approaches
Implementing reactive programming in Java
Understanding Reactive Streams
Exploring the Reactor framework
Using Mono to emit one element
Using Flux to emit multiple elements
Creating Reactive web applications with Spring Web Reactive
Creating a project using Spring Initializr
Creating a reactive controller – StockPriceEventController
Creating an HTML view – stock-price.html
Launching SpringReactiveExampleApplication
Integrating with reactive databases
Integrating the Spring Boot Reactive MongoDB starter
Creating a model object – a stock document
Creating ReactiveCrudRepository
Initializing stock data using CommandLineRunner
Creating reactive methods in the REST controller
Updating the view to subscribe to the event stream
Launching SpringReactiveExampleApplication
Summary
Spring Best Practices
Adhering to Maven's standard directory layout
Building applications using a layered architecture
Having separate context files for different layers
Separating api and impl for important layers
Understanding exception handling best practices
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 for mandatory dependencies
Managing dependency versions for Spring projects
Exploring unit testing best practices
Writing tests for the business layer
Writing tests for the web layer
Writing tests for the data layer
Other application development best practices
Exploring integration testing best practices
Using Spring Session to manage session
Implementing Spring Session with Redis
Adding dependencies for Spring Session
Configuring the filter to replace a HttpSession with Spring Session
Enabling filtering for Tomcat by extending AbstractHttpSessionApplicationInitializer
Exploring caching best practices
Adding the spring-boot-starter-cache dependency
Adding caching annotations
Understanding best practices for logging
Using the Logback framework
log4j2
Providing framework independent configuration
Summary
Working with Kotlin in Spring
Technical requirements
Getting started with Kotlin
Comparing Kotlin and Java
Creating variables and understanding type inference
Understanding the immutability of variables
A quick look at the type system
Understanding null safety
Defining functions in Kotlin
Playing with arrays
Exploring Kotlin collections
No checked exceptions
Using a data class for beans
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
Adding dependencies and plugins to pom.xml
Spring Boot application class
Spring Boot application test class
Implementing the REST service using Kotlin
A simple method returning a string
Writing a unit test
Writing an integration test
Simple REST method returning an object
Executing a request
Writing a unit test
Writing an integration test
GET method with path variables
Executing a request
Writing a unit test
Writing an integration test
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Spring Framework revolutionized enterprise application development in the Java world. It has been the framework of choice for almost 15 years. This book will help you understand this evolution—from solving the problems of building testable loosely coupled applications to building web applications and REST APIs. Today, various Spring Projects are available to help you build cloud-native microservices and API backends for full stack applications. We will look at some of the important Spring Projects in depth—Spring Framework, Spring Boot, Spring Cloud, Spring Data, Spring Reactive, Spring Security, and Spring Test. We will build a web application, a Todo REST API, several cloud-native microservices, and a basic full stack application to understand the various Spring Projects. Advanced features of Spring Boot will also be covered and demonstrated through powerful examples.
By the end of this book, you will be equipped with the knowledge and best practices to develop applications with Spring, Spring Boot, and Spring Cloud.
This book is for experienced Java developers with a basic knowledge of Spring Framework. In this book, we dig deeper into various Spring Projects—Spring Framework, Spring Boot, Spring Cloud, Spring Data, Spring Reactive, Spring Security, and Spring Test. This book will help you develop and unit test an awesome REST API, microservices, full stack applications, and cloud-native applications with Spring Framework.
Chapter 1, Spring Landscape – Framework, Modules, and Projects, takes you through the evolution of Spring Framework, ranging from its initial versions to Spring 5.1. Initially, Spring was used to develop testable applications using dependency injection and core modules. Recent Spring Projects, such as Spring Boot, Spring Cloud, and Spring Cloud Data Flow deal with application infrastructure and moving applications to the cloud. You'll get an overview of different Spring modules and Projects.
Chapter 2, Dependency Injection and Unit Testing, dives deep into dependency injection, looking at the different kinds of dependency injection methods available in Spring, and how auto-wiring makes life easier. This chapter also takes a quick look at unit testing.
Chapter 3, Building Web Applications with Spring MVC, gives an overview of building web applications with the most popular Java web framework—Spring MVC. The beauty of Spring MVC lies in its clean, loosely coupled architecture. With a clean definition of roles for controllers, handler mappings, view resolvers, and Plain Old Java Object (POJO) command beans, Spring MVC makes use of all the core Spring features, such as dependency injection and auto-wiring, to make it simple to create servlet-based web applications.
Chapter 4, Getting Started with Spring Boot, introduces Spring Boot and discusses how it makes it easy to develop production-grade Spring-based applications. You will learn the basics of Spring Boot—Spring Initializr, auto-configuration, and starter Projects. You will use Spring Boot Actuator to monitor your applications and use Spring Boot DevTools to become a productive developer.
Chapter 5, Digging Deeper into Spring Framework, digs deeper into Spring Framework. You will learn about implementing cross-cutting concerns with Spring AOP (short for Aspect Oriented Programming). You will also learn how to schedule tasks and write dynamic scripts using Groovy and JavaScript with the JSR 223 API.
Chapter 6, Building REST APIs with Spring Boot, focuses on building great REST APIs with Spring Boot. You will start by implementing a basic REST API and then move on to adding caching, exception handling, HATEOAS, and internationalization, while making use of different features from Spring and Spring Boot frameworks.
Chapter 7, Unit Testing REST APIs with Spring Boot, focuses on writing great unit and integration tests for REST APIs developed with Spring Boot. You'll learn how to use Spring MockMVC and Spring Boot Test to write unit tests with mocks and integration tests launching entire Spring contexts.
Chapter 8, Securing REST APIs with Spring Security, looks at the most important REST API features—authentication and authorization. Spring Security is the framework of choice for securing REST APIs in the Java world—especially for applications built with Spring and Spring Boot. You'll gain an understanding of how to integrate Spring Security into a Spring Boot REST API project. You will then learn about the key building blocks behind Spring Security—filters, authentication managers, providers, and access decision managers. This chapter covers basic authentication, OAuth, and using JWT with Spring Security OAuth.
Chapter 9, Full Stack App with React and Spring Boot, shifts our attention to full stack applications. You will create a simple frontend application with one of the popular frontend frameworks—React—and integrate it with a Spring Boot backend. The chapter covers various challenges that you may face when doing full stack development—including security.
Chapter 10, Managing Data with Spring Data, focuses on the Spring Data module. Spring Data aims to introduce a common approach to talking to a wide variety of data stores—relational or otherwise. You will develop simple applications to integrate Spring with JPA and big data technologies.
Chapter 11, Getting Started with Microservices, explains the evolution of application architectures in the last decade. You will gain an understanding of why microservices and cloud-native applications are needed and get a quick overview of the different Spring Projects that can help you build cloud-native applications.
Chapter 12, Building Microservices with Spring Boot and Spring Cloud, looks at implementing microservices using projects under the Spring Cloud umbrella. We will look at configuration management, service discovery, circuit breakers, and intelligent routing. You will use Spring Cloud Config, Spring Cloud Bus, Ribbon, Eureka, Zuul, Spring Cloud Sleuth, Zipkin, and Hystrix to implement a microservice.
Chapter 13, Reactive Programming, explores programming with asynchronous data streams. In this chapter, you will gain an understanding of reactive programming. The chapter also takes a quick look at the features provided by Spring Framework.
Chapter 14, Spring Best Practices, introduces best practices for developing enterprise applications with Spring, related to unit testing, integration testing, maintaining a Spring configuration, and more.
Chapter 15, Working with Kotlin in Spring, introduces you to a JVM language that is quickly gaining popularity—Kotlin. This chapter offers guidance on how to set up a Kotlin project in Eclipse. You will create a new Spring Boot project using Kotlin and implement a couple of basic services with unit and integration testing.
To get the most out of this book, you need to be an experienced Java programmer.
To be able to run through the examples in this book, you will need the following tools:
Java 8/9/10/11/12
Eclipse IDE
Postman
We will use Maven embedded into Eclipse IDE to download all the dependencies that are needed.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
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.1. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789615692_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "We are defining a component scan for the com.mastering.spring.springmvc package so that all the beans and controllers in this package are created and autowired."
A block of code is set as follows:
<beans > <!-Schema Definition removed --> <context:component-scan base-package="com.mastering.spring.springmvc" /> <mvc:annotation-driven /> </beans>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public class User { private String guid;
private String name;
private String userId; private String password; private String password2; //Constructor //Getters and Setters //toString }
Any command-line input or output is written as follows:
mvn cf:push
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Click on the Install button shown in the following screenshot."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
The Spring framework revolutionized enterprise application development in the Java world. It has continued to be the framework of choice for almost 15 years.
This section will help you get started with the two most important Spring Projects: Spring Framework and Spring Boot. We will understand the modularity of the Spring Framework and discuss several Spring Modules.
The following chapters are covered under this section:
Chapter 1
,
Spring Landscape – Framework, Modules, and Projects
Chapter 2
,
Dependency Injection and Unit Testing
Chapter 3
,
Building Web Applications with Spring MVC
Chapter 4
,
Getting Started with Spring Boot
Chapter 5
,
Digging Deeper into the Spring Framework
The first version of Spring Framework 1.0 was released in March 2004. In the last decade and a half, the Spring Framework remains the number one framework of choice to develop enterprise applications in the Java world.
In this chapter, we will take a 10,000 feet look at the journey of the Spring Framework.
The Spring Framework is highly modular with more than 20 different modules. Spring Modules provide the core features of the Spring Framework—Dependency Injection (DI), the Web MVC Framework, AOP, and more. Spring Modules help you to pick and choose the modules you want to use.
Architectures have continuously evolved during the last decade. Almost all enterprises are on the journey from monolith architectures to microservices architectures. The Spring Framework evolved continuously to keep up with the needs of enterprise applications.
Spring Projects explore solutions to the evolving challenges in enterprises. Some of the important Spring Projects are Spring Boot, Spring Cloud, Spring Data, Spring Batch, and Spring Security.
In this chapter, we will get a big picture of the entire Spring landscape—including the evolution of important Spring Modules and Spring Projects.We will end the chapter by looking at the new features in Spring Framework 5.0 and 5.1.
The following topics will be covered in this chapter:
Why the Spring Framework is popular
How the Spring Framework has adapted to the evolution of application architectures
What the important modules in the Spring Framework are
Where the Spring Framework fits in the umbrella of Spring Projects
What the new features in Spring Framework 5.0 and 5.1 are
Spring has been the number one framework of choice to develop enterprise applications in the Java world for more than a decade. In the relatively young and dynamic world of Java frameworks, a decade is a long time.
Enterprise applications evolve quickly. The main challenges in 2004, when the first version of the Spring Framework was initially released, were the difficulties in writing testable code and developing loosely coupled web applications. As time progressed, the challenges shifted to developing great web services—initially with Simple Object Access Protocol (SOAP) and, eventually, REST. And, in the last few years, enterprise application architectures evolved toward microservices.
The Spring Framework (including Spring Projects and Spring Modules) continues to provide solutions to meet the needs of the day with a number of Spring Projects and Spring Modules, including Spring Core, Spring MVC, Spring Web Services, Spring Boot, and Spring Cloud.
How did Spring remain so popular in a dynamic world where frameworks struggle to be relevant for more than a few years?
In this section, let's take a quick look at how the Spring Framework has kept up with the changing needs of enterprise applications.
Java EE applications in the early 2000s were cumbersome to write and test. It was difficult to develop loosely coupled applications. Unit testing was near impossible for enterprise applications with external connections such as a database. Testing even simple features involved deploying the entire application in a container.
The Spring Framework was introduced, in 2004, as a lightweight framework aimed at making developing Java EE applications simpler.
The Spring website (https://projects.spring.io/spring-framework/) defines the Spring Framework as follows:
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.
The crux of the Framework is a concept called DI or Inversion of Control (IoC).
Any Java class we write depends on other classes. The other classes a class depends on are its dependencies. If a class directly creates instances of dependencies, a tight coupling is established between them. With Spring, the responsibility of creating and wiring objects is taken over by a new component called the IoC Container. Classes define dependencies and the Spring IoC Container creates objects and wires the dependencies together. This revolutionary concept, where the control of creating and wiring dependencies is taken over by the container, is famously called IoC or DI. We will discuss dependency injection in complete detail in Chapter 2, Dependency Injection and Unit Testing.
The initial version of Spring also provided a very good framework to develop web applications—Spring MVC.
Let's quickly look at the reasons behind the initial popularity of the Spring Framework:
Loose coupling and testability
Architectural flexibility
Reduction in plumbing code
Let's discuss each of these in detail.
Through DI, Spring brings loose coupling between classes. While loose coupling is beneficial for application maintainability in the long run, the first benefits are realized with the testability that it brings in.
Earlier versions of Java EE applications were very difficult to unit test. In fact, it was difficult to test code outside of the container. The only way to test code was to deploy them in a container.
DI 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
(
CI
) builds, preventing future defects
The Spring Framework is highly modular, having more than 20 different modules—all with clearly defined boundaries. This allows applications to pick and choose the features (or the module) of the framework they would want to use. These modules are called Spring Modules. We will look at Spring Modules in detail a little later in this chapter.
In addition, the Spring Framework does not aim 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.
Let's consider a few examples:
If you would want to build an awesome web application, 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
Enterprise JavaBeans
(
EJBs
) as well.
To talk to a database, Spring provides its own module—the Spring JDBC module. However, Spring has great support for any of your preferred data layer frameworks
—
Java Persistence API
(
JPA
), Hibernate (with or without JPA), or iBatis.
Spring provides a basic
Aspect Oriented Framework
(
AOP
) called Spring AOP to implement your cross-cutting concerns (logging, transaction management, security, and more). It also provides the option to integrate with a full-fledged AOP implementation such as AspectJ.
In the previous section, we discussed how the first version of Spring brought a breath of fresh air to the Java EE world. In this section, let's look at how Spring evolved with the next versions of the Spring Framework.
An important thing Spring brings in is the umbrella of Spring Projects. While the Spring Framework provides the base for core features of enterprise applications (DI, web, and data), other Spring Projects explore integration and solutions to other problems in the enterprise space. Spring Projects helped Spring to stay ahead of the game by allowing innovation outside the core Spring Framework. We will discuss the important Spring Projects in a separate section in this chapter.
As we move toward the last few years of the 2000 decade, enterprise applications started moving toward web services—initially SOAP Web Services and, by the end of the decade, toward RESTful web services.
Spring continued to evolve as follows:
Introduced a Spring Project called Spring Web Services—to help the development of contract-first SOAP web services
Enhanced the Spring MVC Module with excellent support for REST web services
In addition to providing excellent support for web services, Spring stayed ahead of Java EE by providing new features:
Annotations were introduced in Java 5. The Spring Framework (version 2.5—November 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 (December 2009—2 years) before having comparable functionality.
The Spring Framework introduced a number of abstractions ahead of Java EE to keep the application decoupled from specific implementation. The 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.
One of the Spring Projects called Spring Batch defines a new approach to building Java Batch applications. We had to wait until Java EE 7 (June 2013) to have a comparable batch application specification in Java EE.
In the previous sections, we looked at how Spring evolved to meet the enterprise application needs of the late 2000s—RESTful and SOAP web services and staying ahead of Java EE.
We've evolved further in the last few years and the enterprise needs today are very different from a decade ago. Over a period of time, applications grew into monoliths, which became difficult to manage. The challenges with monolith applications lead to organizations searching for the silver bullet.
In the last few years, a common pattern emerged among all of the organizations that were successful at doing this. From this emerged an architectural style that was called microservices architecture. We will discuss microservices inChapter 11, Getting Started with Microservices.
Microservices architecture involves building a number of small, independently deployable microservices. These bring in a couple of new challenges:
How can we quickly build microservices?
How can we connect the microservice to the cloud?
Let's discuss the solution Spring provides to these problems.
In the era of monoliths, we had the luxury of taking time to set the frameworks up for an application. However, in the era of microservices, we would want to create individual components faster. Spring Boot project aims to solve this problem.
Let's consider an example—I want to build a RESTful API microservice using Spring MVC and JPA (Hibernate). What are the things I would need to do? Let's take a quick look:
You would need to decide the compatible versions of Spring MVC, JPA, and Hibernate to use
You would need to start setting up Spring Context with all of the different layers integrated—the web layer, business layer, and data layer
You would need to decide how to do
configuration management, unit testing, transaction management, logging, and security
This would take a few weeks at least. And, in the microservices world, we do not have weeks. And that's the problem Spring Boot aims to solve.
As the official website highlights:
Spring Boot aims to take an opinionated view—basically making a lot of decisions for us—on developing Spring-based projects. We will talk about Spring Boot in depth in Chapter 5, Digging Deeper into the Spring Framework.
The cloud comes with its own set of challenges. Spring Cloud aims to provide solutions to some commonly encountered patterns when building systems on the cloud:
Configuration management
: All applications have configuration that varies from one environment to another environment. Configuration is typically littered at multiple locations—application code, property files, databases, environment variables,
Java Naming and Directory Interface
(
JNDI
), and system variables are a few examples. With microservices architectures, the problem of configuration management becomes multi fold. Spring Cloud provides a centralized configuration management solution for microservices called Spring Cloud Config.
Service discovery
: Service discovery promotes loose coupling between services. Spring Cloud provides integration with popular service discovery options such as Eureka, ZooKeeper, and Consul.
Circuit breakers
: Microservices must be fault tolerant. They should be able to handle the failure of backing services gracefully. Circuit breakers play a key role in providing a default minimal service in the case of failures. Spring Cloud provides integration with the Netflix Hystrix fault tolerance library.
API gateways
: An API gateway provides centralized aggregation, routing, and caching services. Spring Cloud provides integration with the API gateway library, Netflix Zuul.
We will explore Spring Cloud in depth in Chapter 11, Getting Started with Microservices.
In this section, we looked at how Spring evolved to meet enterprise application needs during the last 15 years. What started off as a simple framework to enable testability with loosely coupled code evolved into a complete landscape of Projects and Modules, enabling the enterprise to develop web services, such as RESTful and SOAP—and microservices.
In the subsequent sections, let's take a deeper look at the important Spring Modules and Spring Projects.
The modularity of the Spring Framework is one of the most important reasons for its widespread use. The Spring Framework is highly modular with more than 20 different modules having clearly defined boundaries.
The following diagram shows different Spring Modules, organized by the layer of application they are typically used in:
We will start by discussing the Spring Core Container before moving on to other modules grouped by the application layer they are typically used in.
Spring Core Container provides the core features of the Spring Framework—DI, the IoC Container, and the application context. We will learn more about DI and the IoC container in Chapter 2, Dependency Injection and Unit Testing.
Important core Spring Modules are listed as follows:
spring-core
: This is for utilities used by other Spring Modules.
spring-beans
: This provides support for Spring Beans. In combination with
spring-core
