34,79 €
With growing demands, organizations are looking for systems that are robust and scalable. Therefore, the Spring Framework has become the most popular framework for Java development. It not only simplifies software development but also improves developer productivity. This book covers effective ways to develop robust applications in Java using Spring.
The book has three parts, where each one covers the building of a comprehensive project in Java and Spring. In the first part, you will construct a CMS Portal using Spring's support for building REST APIs. You will also learn to integrate these APIs with AngularJS and later develop this application in a reactive fashion using Project Reactor, Spring WebFlux, and Spring Data. In the second part, you’ll understand how to build a messaging application, which will consume the Twitter API and perform filtering and transformations. Here, you will also learn about server-sent events and explore Spring’s support for Kotlin, which makes application development quick and efficient. In the last part, you will build a real microservice application using the most important techniques and patterns such as service discovery, circuit breakers, security, data streams, monitoring, and a lot more from this architectural style.
By the end of the book, you will be confident about using Spring to build your applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 328
Veröffentlichungsjahr: 2018
Copyright © 2018 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: Aaron LazarAcquisition Editor: Chaitanya NairContent Development Editor: Lawrence VeigasTechnical Editor: Adhithya HaridasCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jisha ChirayilProduction Coordinator: Aparna Bhagat
First published: February 2018
Production reference: 1230218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-439-8
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,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
Mapt is fully searchable
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.PacktPub.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.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.
Claudio Eduardo de Oliveira is a software architect and software developer working for Sensedia. He works with APIs, microservices, and cloud-centric applications. He has more than ten years of experience in software development with Java and JVM languages. He is a speaker at some important events in Brazil about Spring and other Java Frameworks.
Paulo Zanco is a solution architect working for Daitan Labs. He is also a system architect with over 25 years of experience at national and international large/middle-sized companies. He has led many complex projects consisting of medium and large teams. He has extensive experience of designing and developing object-oriented and services systems. He is also certified by Sun and Oracle, in J2EE and SOA technologies. He holds a Master's degree in Management Information Systems from Pontifícia Universidade Católica de Campinas.
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
Spring 5.0 By Example
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
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
Journey to the Spring World
Spring modularity
Spring Core Framework
Core container
Spring Messaging
Spring AMQP
Spring for Apache Kafka
Spring JMS
Spring Web MVC
Spring WebFlux
Spring Data
Spring Security
Spring Cloud
Spring Cloud Netflix
Spring Cloud Config
Spring Cloud Consul
Spring Cloud Security
Spring Cloud Bus
Spring Cloud Stream
Spring Integration
Spring Boot
Microservices and Spring Boot
Setting up our development environment
Installing OpenJDK
Installing Maven
Installing IDE
IntelliJ IDEA
Spring Tools Suite
Installing Docker
Introducing Docker concepts
Docker images
Containers
Docker networks
Docker volumes
Docker commands
Docker run
Docker container
Docker network
Docker volume
Summary
Starting in the Spring World – the CMS Application
Creating the CMS application structure
The CMS project
Project metadata section
The dependencies section
Generating the project
Running the application
Looking under the hood
Running the application
IntelliJ IDEA
Command line
Command line via the Maven goal
Command line via the JAR file
Creating the REST resources
Models
Adding Lombok dependency
Creating the models
Tag
Category
User
News
Hello REST resources
Creating the CategoryResource class
UserResource
NewsResource
Adding service layer
Changes in the model
Adding a new review
Keeping the news safely
Before starting the service layer
CategoryService
UserService
NewsService
Configuring Swagger for our APIs
Adding dependencies to pom.xml
Configuring Swagger
First documented API
Integrate with AngularJS
AngularJS concepts
Controllers
Services
Creating the application entry point
Creating the Category Controller
Creating the Category Service
Summary
Persistence with Spring Data and Reactive Fashion
Learning the basics of Docker
Preparing  MongoDB
Preparing a PostgreSQL database
Spring Data project
Spring Data JPA
Configuring pom.xml for Spring Data JPA
Configuring the Postgres connections
Mapping the models
Adding the JPA repositories in the CMS application
Configuring transactions
Installing and configuring pgAdmin3
Checking the data on the database structure
Creating the final data access layer
Spring Data MongoDB
Removing the PostgreSQL and Spring Data JPA dependencies
Mapping the domain model
Configuring the database connection
Adding the repository layer
Checking the persistence
Creating the Docker image for CMS
Configuring the docker-maven-plugin
Adding the plugin on pom.xml
Pushing the image to Docker Hub
Configuring the Docker Spring profile
Running the Dockerized CMS
Putting in Reactive fashion
Reactive Spring
Project Reactor
Components
Hot and cold
Reactive types
Let's play with the Reactor
Spring WebFlux
Event-loop model
Spring Data for Reactive Extensions
Spring Data Reactive
Reactive repositories in practice
Creating the first Reactive repository
Fixing the service layer
Changing the CategoryService
Changing the REST layer
Adding the Spring WebFlux dependency
Changing the CategoryResource
Summary
Kotlin Basics and Spring Data Redis
Learning Kotlin basics
Main characteristics of Kotlin
Syntax
Semantics
Declaring functions in Kotlin
Simple function with parameters and return type
Simple function without return
Single expressions functions
Overriding a function
Data classes
Objects
Companion objects
Kotlin idioms
String interpolation
Smart Casts
Range expressions
Simple case
The until case
The downTo case
Step case
Null safety
Safe calls
Elvis operator
Wrapping it up
Creating the project
Project use case
Creating the project with Spring Initializr
Adding Jackson for Kotlin
Looking for the Maven plugins for Kotlin
Creating a Docker network for our application
Pulling the Redis image from the Docker Hub
Running the Redis instance
Configuring the redis-cli  tool
Understanding Redis
Data types
Strings
Main commands
Lists
Main commands
Sets
Main commands
Spring Data Reactive Redis
Configuring the ReactiveRedisConnectionFactory
Providing a ReactiveRedisTemplate
Creating Tracked Hashtag repository
Creating the service layer
Exposing the REST resources
Creating a Twitter application
Configuring pom.xml
Creating the image
Running the container
Testing APIs
Summary
Reactive Web Clients
Creating the Twitter Gathering project
Project structure
Starting the RabbitMQ server with Docker
Pulling the RabbitMQ image from Docker Hub
Starting the RabbitMQ server
Spring Messaging AMQP
Adding Spring AMQP in our pom.xml
Integrating Spring Application and RabbitMQ
Understanding RabbitMQ exchanges, queues, and bindings
Exchanges
Direct exchanges
Fanout exchanges
Topic exchanges
Header exchanges
Queues
Bindings
Configuring exchanges, queues, and bindings on Spring AMQP
Declaring exchanges, queues, and bindings in yaml
Declaring Spring beans for RabbitMQ
Consuming messages with Spring Messaging
Producing messages with Spring Messaging
Enabling Twitter in our application
Producing Twitter credentials
Configuring Twitter credentials in application.yaml
Modelling objects to represent Twitter settings
Twittertoken
TwitterAppSettings
Declaring Twitter credentials for the Spring container
Spring reactive web clients
Producing WebClient in a Spring Way
Creating the models to gather Tweets
Authentication with Twitter APIs
Some words about server-sent events (SSE)
Creating the gather service
Listening to the Rabbit Queue and consuming the Twitter API
Changing the Tracked Hashtag Service
Adding the Spring Starter RabbitMQ dependency
Configuring the RabbitMQ connections
Creating exchanges, queues, and bindings for the Twitter Hashtag Service
Sending the messages to the broker
Testing the microservice's integrations
Running Tracked Hashtag Service
Running the Twitter Gathering
Testing stuff
Spring Actuator
Adding Spring Boot Actuator in our pom.xml
Actuator Endpoints
Application custom information
Testing endpoints
Summary
Playing with Server-Sent Events
Creating the Tweet Dispatcher project
Using Spring Initializr once again
Additional dependencies
Server-Sent Events
A few words about the HTTP protocol
HTTP and persistent connections
WebSockets
Server-Sent Events
Reactor RabbitMQ
Understanding the Reactor RabbitMQ
Configuring RabbitMQ Reactor beans
Consuming the RabbitMQ queues reactively
Filtering streams
Dockerizing the whole solution
Tweet Gathering
Tweet Dispatcher
Running the containerized solution
Running the Tracked Hashtag Service container
Running the Tweet Gathering container
Running the Tweet Dispatcher container
The docker-compose tool
Installing docker-compose
Creating a docker-compose file
Running the solution
Testing the network
Summary
Airline Ticket System
The Airline Ticket System
Airline functionalities
Solution diagram
Spring Cloud Config Server
Creating the Config Server project
Enabling Spring Cloud Config Server
Using GitHub as a repository
Configuring the Spring Boot application
Configuring the Git repository as a properties source
Running the Config Server
Testing our Config Server
Spring Cloud service discovery
Creating Spring Cloud Eureka
Creating the Eureka server main class
Configuring the Spring Cloud Eureka server
Running the Spring Cloud Eureka server
Spring Cloud Zipkin server and Sleuth
Infrastructure for the Zipkin server
Creating the Spring Cloud Zipkin server
Configuring boostrap.yaml and application.yaml
Running the Zipkin server
Spring Cloud Gateway
Creating the Spring Cloud Gateway project
Creating the Spring Cloud Gateway main class
Configuring the Spring Cloud Gateway project
Running the Spring Cloud Gateway
Checking the Eureka server
Creating our first route with Spring Cloud Gateway
Putting the infrastructure on Docker
Summary
Circuit Breakers and Security
Understanding the service discovery power
Creating the planes microservice
Coding the planes microservice
The reactive repository
Creating the Plane service
The REST layer
Running the plane microservice
Flights microservice
Cloning the Flight microservice project
Netflix Ribbon
Understanding the discovery client
Service discovery and load balancing in practice
When the services fail, hello Hystrix
Hystrix in a nutshell
Spring Cloud Hystrix
Spring Boot Admin
Running Spring Boot Admin
Spring Cloud Zuul
Understanding the EDGE service project
Creating the EDGE server
Summary
Putting It All Together
The airline Bookings microservice
The airline Payments microservice
Learning about the Turbine server
Creating the Turbine server microservice
Hystrix Dashboard
Creating the Mail microservice
Creating the SendGrid account
Creating the Mail microservice project
Adding RabbitMQ dependencies
Configuring some RabbitMQ stuff
Modeling a Mail message
The MailSender class
Creating the RabbitMQ queue listener
Running the Mail microservice
Creating the Authentication microservice
Creating the Auth microservice
Configuring the security
Testing the Auth microservice
Client credentials flow
Implicit grant flow
Protecting the microservices with OAuth 2.0
Adding the security dependency
Configuring the application.yaml file
Creating the JwtTokenStore Bean
Monitoring the microservices
Collecting metrics with Zipkin
Collection commands statistics with Hystrix
Dockerizing the microservices
Running the system
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
With growing demands, organizations are looking for systems that are robust and scalable. Hence the Spring Framework has become the most popular framework for Java development. It not only simplifies software development but also improves developer productivity. This book covers effective ways to develop robust applications in Java using Spring.
Developers who are starting out with Spring will learn about the new Spring 5.0 framework concepts followed by their implementation in Java and Kotlin. The book will also help experienced Spring developers gain insights into the new features added in Spring 5.0.
Chapter 1, Journey to the Spring World, will guide you through the main concepts of Spring Framework. Here we learn to setup the environment by installing OpenJDK, Maven, IntelliJ IDEA, and Docker. By the end, we will create our first Spring application.
Chapter 2, Starting in the Spring World – the CMS Application, will begin by getting our hands dirty with Spring Initializr to create configurations for our CMS application. We will then learn how to create REST resources, add the service layer and finally integrate with AngularJS.
Chapter 3, Persistence with Spring Data and Reactive Fashion, will build upon our CMS application created in the previous chapter. Here we will learn how to persist data on a real database by learning about Spring Data Reactive MongoDB and PostgresSQL. We will finally learn about Project Reactor which will help you to create a non-blocking application in the JVM ecosystem.
Chapter 4, Kotlin Basics and Spring Data Redis, will give you a basic introduction to Kotlin while presenting the benefits of the language. We will then learn how to use Redis which will be used as a message broker using the publish-subscribe feature.
Chapter 5, Reactive Web Clients, will teach you how to use the Spring Reactive Web Client and make HTTP calls in a reactive fashion. We will also be introduced to RabbitMQ and Spring Actuator.
Chapter 6, Playing with Server-Sent Events, will help you develop an application which will filter tweets by text content. We will accomplish this by consuming the tweeter steam using Server-Sent Events which is a standard way to send data streams from a server to clients
Chapter 7, Airline Ticket System, will teach you to use Spring Messaging, WebFlux, and Spring Data components to build a airline ticket system. You will also learn about circuit breakers and OAuth in this chapter. By the end, we will create a system with many microservices to ensure scalability.
Chapter 8, Circuit Breakers and Security, will help you discover how to apply service discovery features for our business microservices while also understanding how the Circuit Breaker pattern can help us to bring resilience to our applications.
Chapter 9, Putting It All Together, will bring the entire book into perspective while also teaching you about the Turbine server. We will also look into the Hystrix Dashboard to monitor our different microservices to ensure maintainability and optimum performance of our applications.
The readers are expected to have a basic knowledge of Java. Notion about Distributed Systems is an added advantage.
To execute code files in this book, you would need to have the following software/dependencies:
IntelliJ IDEA Community Edition
Docker CE
pgAdmin
Docker Compose
You will be assisted with installation processes,etc through this book.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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 athttps://github.com/PacktPublishing/Spring-5.0-By-Example. We also have other code bundles from our rich catalog of books and videos available athttps://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://www.packtpub.com/sites/default/files/downloads/Spring50ByExample_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: "It includes the infrastructure connections which are configured in the default profile in application.yaml."
A block of code is set as follows:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId></dependency>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
management:
endpoints:
web:
expose: "*"
Any command-line input or output is written as follows:
docker-compose up -d
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: "The next screen will be shown and we can configure the Environment Variable:"
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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 packtpub.com.
Spring is an open source modular framework for the JVM platform. A framework is a collection of libraries whose primary goal is to address common software development problems. The framework should solve these problems in a generic form.
Rod Johnson created the Spring Framework in 2002 together with his book publication, which was called Expert One-on-One J2EE Design and Development. The idea behind the creation of the framework was to tackle the complexities of Java Enterprise Edition.
At that time, this kind of solution-focused a lot on the details of the infrastructure, and a developer using the solution would spend a lot of time writing code to solve infrastructural problems. Since its creation, one ofRod Johnson's primary concerns has been to increase developer productivity.
The framework was first seen as a lightweight container for Java Runtime Environment, and it became popular in the community, especially because of the dependency injection feature. The framework made dependency injection incredibly easy. Developers hadn't seen such a feature before, and as a consequence, people the world over adopted the project. Year by year, its popularity within the software development world has been increasing.
In the earliest versions, the framework had to work with the XML file to configure the container. At the time, this was so much better than J2EE applications, where it was necessary to create many Ant files to create the boilerplate classes and interfaces.
The framework was always seen as an advanced technology for the Java platform, but in 2014, the Spring team launched the Spring Boot platform. This platform was incredibly successful in the Java Enterprise ecosystem, and it changed the way in which developers built Java Enterprise applications.
Today, Spring is the de facto framework for Java development, and companies around the world use it in their systems. The community is vibrant and contributes to development in different ways, such as opening issues, adding the code, and discussing the framework in the most important Java conferences around the world. Let's look at and play with the famous framework for Java developers.
We will cover the following topics in this chapter:
Main modules of the Spring Framework
Spring annotations for each module
Setting up the development environment
Docker and Docker commands
Since its foundation, the framework has had a particular focus on modularity. It is an important framework characteristic because it makes the framework an excellent option for different architectural styles and different parts of applications.
It means the framework is not an opinionated, full-stack framework that dictates the rules to make everything work. We can use the framework as we need and integrate it with a wide range of specification and third-party libraries.
For example, for portal web applications, the Spring MVC supports features such as template engines and REST endpoints and integrates them with the popular JavaScript framework, AngularJS.
Also, if the application needs support for a distributed system, the framework can supply an amazing module called Spring Cloud, which has some essential features for distributed environments, such as service registration and discovery, a circuit breaker, intelligent routing, and client-side load balancing.
Spring makes the development applications for Java Runtime easy with different languages, such as Java, Kotlin, and Groovy (with which you can choose the flavor and make the development task fun).
It is divided into various modules. The main modules are as follows:
Spring Core
Spring Data
Spring Security
Spring Cloud
Spring Web-MVC
In this book, we will cover the most common solutions involved in Java Enterprise applications, including the awesome Spring Cloud project. Also, we can find some interesting projects such as Spring Batch and Spring Integration, but these projects are for specific needs.
This module is the base of the framework and contains the essential support for dependency injection, web features supported by Spring MVC (model-view-controller) and the pretty new WebFlux frameworks, and aspect-oriented programming. Also, this module supports the foundation for JDBC, JMS, JPA and a declarative way to manage transactions. We will explore it and understand the main projects of this module. So let's do it!
The core container is the basis of the whole Spring ecosystem and comprehends four components—core, beans, context, and expression language.
Core and beans are responsible for providing the fundamentals of the framework and dependency injection. These modules are responsible for managing the IoC container, and the principal functions are the instantiation, configuration, and destruction of the object residents in the Spring container.
There are two critical interfaces inside these modules—BeanFactory and ApplicationContext. The BeanFactory takes care of the bean lifecycle, instantiating, configuring, managing, and destroying, and the ApplicationContext helps developers to work with files resources in a generic way, enable to publish events to registered listeners. Also, the ApplicationContext supports internationalization and has the ability to work with messages in different Locales.
These modules help the context component to provide a way to access the objects inside the container. The context component has the ApplicationContext interface with the essential class for the container.
Spring Framework supports a wide range of messaging systems. The Java platform is recognized as providing excellent support for messaging applications, and Spring Framework follows this approach and offers a variety of projects to help developers to write powerful applications with more productivity and fewer lines of infrastructure code. The basic idea of these projects is to provide some template classes that have the convenience methods to interact with the messaging systems.
Also, the project supplies some listener annotations to provide support for listening to messages from the brokers. The framework maintains the standard for different projects. In general, the prefix of the annotations is the name of the messaging system, for example, @KafkaListener.
The framework supplies many abstractions to create messaging applications in a generic way. This is interesting stuff because the application requirements change during the application lifecycle and the message broker solution may change as well. Then, with small changes, the application built with the Spring message module can work in different brokers. This is the goal.
This subproject supports the AMQP protocol in Spring Framework. It provides a template to interact with the message broker. A template is like a super high-level API that supports the send and receive operations.
There are two projects in this set: spring-amqp, which can be used for ActiveMQ for instance, and spring-rabbit, which adds support for the RabbitMQ broker. This project enables broker administration through the APIs to declare queues, bindings, and exchanges.
These projects encourage the extensive use of dependency injection provided by the core container, because they make the configuration more declarative and easy to understand.
Nowadays, the RabbitMQ broker is the popular choice for the messaging applications, and Spring provides full support for client interactions up to the level of administration tasks.
Spring for Apache Kafka supports the broker-based Apache Kafka applications. It provides a high-level API to interact with Apache Kafka. Internally, the projects use the Kafka Java APIs.
This module supports the annotation programming model. The basic idea is that with a couple of annotations and some POJO models, we can bootstrap the application and start listening to and producing messages.
KafkaTemplate is a central class of this project. It enables us to send messages to Apache Kafka with a high-level API. Asynchronous programming is supported as well.
This module offers support for transactions via annotations. This feature is enabled via standard transactional annotations used in Spring-based applications, such as @Transactional.
We also learned about Spring AMQP. This project adds the Spring concept of creating applications based on this broker. The dependency injection features are supported as well.
The idea of this project provides a JMS integration with ideas of Spring Framework projects and supplies a high-level API to interact with brokers. The worst part of a JMS specification is that it has a lot of boilerplate code to manage and close connections.
The JmsTemplate is a central class for this module, and it enables us to send messages to the broker. The JMS specification has a lot of intrinsic behaviors to handle the creation and releases resources, for instance, the JmsTemplate class do this tasks automatically for developers.
The module also supports transactional requirements. The JmsTransactionManager is the class that handles the transactional behavior of the Spring JMS module.
Spring removes the boilerplate code with a couple of annotations. The framework increases the readability of the code and makes the code more intuitive as well.
This module is the first one built by the Spring Team to support the web applications in Spring Framework. This module uses the Servlet API as its foundation, and then these web applications must follow the Servlet Specification and be deployed into servlet containers. In version 5.0, the Spring Team created a Reactive web framework, which will be covered later in this book.
The Spring Web MVC module was developed using the front controller pattern. When the framework was created, this pattern was a common choice for many frameworks, such as Struts and JSF, among others. Under the hood, there is the main servlet in Spring called DispatcherServlet. This servlet will redirect through an algorithm to do the desired work.
It enables developers to create amazing web applications on the Java platform. This portion of the framework provides full support to develop this kind of application. There are some interesting features for this purpose, such as support for internationalization and support for handling cookies. Also, multipart requests are an exciting feature for when the application needs to handle upload files and support routing requests.
These characteristics are common for most web applications, and the framework has excellent support for these features. This support makes the framework a good choice for this kind of application. In Chapter 2, Starting in the Spring World - The CMS Application, we will create an application using this module and the main features will be explored in depth.
The module has full support for annotation programming since to declare HTTP endpoints until to wrap the request attribute in an HTTP request. It makes the application extremely readable without the boilerplate code to get the request parameter, for example.
Web application-wise, it enables developers to work with robust template engines such as Thymeleaf and Freemarker. It is entirely integrated with routing features and bean validation.
Also, the framework allows developers to build REST APIs with this module. Given all of this support, the module has become a favorite in the Spring ecosystem. Developers have started to create APIs with this stack, and some important companies have started to use it, especially given that the framework provides an easy way to navigate through the annotations. Because of this, the Spring Team added the new annotation @RestController in version 4.0.
We will work a lot with this module. Chapter by chapter, we will learn interesting things about this part of the framework.
A new module introduced in Spring 5.0, Spring WebFlux, can be used to implement web applications built with Reactive Streams. These systems have nonblocking characteristics and are deployed in servers built on top of Netty, such as Undertown and servlet containers that support + 3.1.
This module supports annotations based on Spring MVC modules, such as @GetMapping, @PostMapping, and others. This is an important feature that enables us to migrate to this new version. Of course, some adjustments are necessary, such as adding Reactor classes (Mono or Flux).
This module meets the modern web requirements to handle a lot of concurrent channels where the thread-per-request model is not an option.
We will learn about this module in Chapter 3, Adding Persistence with Spring Data and Putting it into Reactive Fashion and implement a fully Reactive application based on Reactive Streams.
Spring Data is an interesting module that provides the easiest way to manage application data with Spring-based programming. The project is an umbrella project, with subprojects to support different databases technologies, even relational and nonrelational databases. The Spring Team supports some databases technologies, such as Apache Cassandra, Apache Solr, Redis, and JPA Specification, and the community maintains the other exciting projects, such as ElasticSearch, Aerospike, DynamoDb, and Couchbase. The full list of projects can be found at http://projects.spring.io/spring-data.
The goal is to remove the boilerplate code from the persistence code. In general, the data access layer is quite similar, even in different projects, differing only in the project model, and Spring Data provides a powerful way to map the domain model and repository abstraction.
There are some central interfaces; they're a kind of marker to instruct the framework to choose the correct implementation. Under the hood, Spring will create a proxy and delegate the correct implementation. The amazing thing here is that developers don't have to write any persistence code and then take care of this code; they simply choose the required technology and Spring takes care of the rest.
The central interfaces are CrudRepository and PagingAndSortingRepository, and their names are self-explanatory. CrudRepository implements the CRUD behaviors, such as create, retrieval, update, and delete. PagingAndSortingRepository is an extension of CrudRepository and adds some features such as paging and sorting. Usually, we will find derivations of these interfaces such as MongoRepository, which interacts with MongoDB database technology.
Security for Java applications was always a pain for developers, especially in Java Enterprise Edition. There was a lot of boilerplate code to look up objects in the application servers, and the security layer was often heavily customized for the application.
In that chaotic scenario, the Spring Team decided to create a Spring Security project to help developers handle the security layer on the Java application.
In the beginning, the project had extensive support for Java Enterprise Edition and integration with EJB 3 security annotations. Nowadays, the project supports many different ways to handle authorization and authentication for Java applications.
Spring Security provides a comprehensive model to add authorization and authentication for Java applications. The framework can be configured with a couple of annotations, which makes the task of adding a security layer extremely easy. The other important characteristics concern how the framework can be extended. There are some interfaces that enable developers to customize the default framework behaviors, and it makes the framework customized for different application requirements.
It is an umbrella project, and it is subdivided into these modules:
spring-security-core
spring-security-remoting
spring-security-web
spring-security-config
spring-security-ldap
spring-security-acl
spring-security-cas
spring-security-openid
spring-security-test
These are the main modules, and there are many other projects to support a wide range of types of authentication. The module covers the following authentication and authorization types:
LDAP
HTTP Basic
OAuth
OAuth2
OpenID
CAAS
JAAS
The module also offers a domain-specific language (DSL) to provide an easy configuration. Let's see a simple example:
http .formLogin() .loginPage("/login") .failureUrl("/login?error") .and() .authorizeRequests() .antMatchers("/signup","/about").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated();
As we can see, the DSL makes the configuration task extremely easy and very understandable.
Spring Security's main features are as follows:
Session management
Protection against attacks (CSRF, session fixation, and others)
Servlet API integration
Authentication and authorization
We will learn more about Spring Security in Chapter 8, Circuit Breakers and Security. We will also put it into practice.
Spring Cloud is another umbrella project. The primary goal of this project is to help developers create distributed systems. Distributed systems have some common problems to solve and, of course, a set of patterns to help us, such as service discovery, circuit breakers, configuration management, intelligent route systems, and distributed sessions. Spring Cloud tools have all these implementations and well-documented projects.
The main projects are as follows:
Spring Cloud Netflix
Spring Cloud Config
Spring Cloud Consul
Spring Cloud Security
Spring Cloud Bus
Spring Cloud Stream
Spring Cloud Netflix is perhaps the most popular Spring module nowadays. This fantastic project allows us to integrate the Spring ecosystem with the Netflix OSS via Spring Boot AutoConfiguration features. The supported Netflix OSS libraries are Eureka for service discovery, Ribbon to enable client-side load balancing, circuit breaker via Hystrix to protect our application from external outages and make the system resilient, the Zuul component provides an intelligent routing and can act as an edge service. Finally, the Feign component can help developers to create HTTP clients for REST APIs with a couple of annotations.
