35,99 €
Take your application development skills to the next level by implementing Spring Boot features effectively
The Spring framework provides great flexibility for Java development, which also results in tedious configuration work. Spring Boot addresses the configuration difficulties of Spring and makes it easy to create standalone, production-grade Spring-based applications.
This practical guide makes the existing development process more efficient. Spring Boot Cookbook 2.0 Second Edition smartly combines all the skills and expertise to efficiently develop, test, deploy, and monitor applications using Spring Boot on premise and in the cloud. We start with an overview of the important Spring Boot features you will learn to create a web application for a RESTful service. Learn to fine-tune the behavior of a web application by learning about custom routes and asset paths and how to modify routing patterns. Address the requirements of a complex enterprise application and cover the creation of custom Spring Boot starters.
This book also includes examples of the new and improved facilities available to create various kinds of tests introduced in Spring Boot 1.4 and 2.0, and gain insights into Spring Boot DevTools. Explore the basics of Spring Boot Cloud modules and various Cloud starters to make applications in “Cloud Native” and take advantage of Service Discovery and Circuit Breakers.
This book is for Java Developers who have good knowledge and understanding of Spring and Java application development.
Alex Antonov is a very passionate technologist with a hunger to learn new tools, languages, techniques, and concepts behind enterprise application design. His specialty lies in designing highly scalable distributed large-scale enterprise systems. He is also a frequent presenter on the topics of architecture and design at conferences such as UberConference, JavaOne, and SpringOne 2GX. Alex joined Orbitz Worldwide in 2004 and in his current role of senior principal engineer, he is responsible for providing technical leadership and guidance in the development of foundational technologies, core libraries, and APIs for enterprise-wide use, as well as being responsible for web application frameworks and developing common practices. Alex has been a long-time Spring user, starting with Spring 2.0.8 all the way to the latest and greatest—Spring Boot. Besides Java, he is also proficient in Ruby/Rails, PHP, and Groovy, and is currently learning Erlang and Go.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 314
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: Zeeyan PinheiroTechnical Editor: Vibhuti GawdeCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: September 2015 Second edition: February 2018
Production reference: 1230218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78712-982-5
www.packtpub.com
This book is dedicated to my son, Evan!
I hope it inspires you to learn, create, reach your goals, conquer challenges, dream big, and to reach for the skies!
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.
Alex Antonov is a very passionate technologist with a hunger to learn new tools, languages, techniques, and concepts behind enterprise application design. His specialty lies in designing highly scalable distributed large-scale enterprise systems. He is also a frequent presenter on the topics of architecture and design at conferences such as UberConference, JavaOne, and SpringOne 2GX.
Alex joined Orbitz Worldwide in 2004 and in his current role of senior principal engineer, he is responsible for providing technical leadership and guidance in the development of foundational technologies, core libraries, and APIs for enterprise-wide use, as well as being responsible for web application frameworks and developing common practices.
Alex has been a long-time Spring user, starting with Spring 2.0.8 all the way to the latest and greatest—Spring Boot. Besides Java, he is also proficient in Ruby/Rails, PHP, and Groovy, and is currently learning Erlang and Go.
I would like to thank all the people who have inspired, supported, and encouraged me through the book writing process. For me, this book represents the ability to take my passion for building software, my appreciation of the Spring family of frameworks, and the amazing work that was done by their creators, combine it with my many years of first-hand experience building complex applications, and share all the thoughts and best practices that I’ve developed over time and always wanted to share, with the community to help them build better, more elegant, robust, and performant applications.
I want to specially thank my wife, Alla, for constantly being there for me, for supporting me in writing this book, for being understanding when I spent countless evenings and weekends working on the chapters, for giving me an extra push to the finish line when I was close to being done, and for just being there for me! Honey, I love you very much!!!
A special thank you goes to my parents for giving me the opportunity to pursue my career dreams, for my education, and for raising me to become the person I am. All your hard work is now paying off and I would not be able to achieve what I have, or written this book, if it weren’t for you. I love you guys a lot, and while you are around, I can still be a child.
Ricky Yim is a passionate software engineer who has over 17 years of industry experience. Ricky is a firm believer in building quality software and using agile practices to solve problems. He takes a flexible approach to software delivery and applies innovative solutions. He is currently the head of technology and delivery at DiUS Computing.
Tejaswini Mandar Jog is a passionate and enthusiastic Java trainer. She has more than 9 years of experience in the IT training field, specializing in Java, J2EE, Spring, and relevant technologies. She has worked with many renowned corporate companies on training and skill enhancement programs. She is also involved in the development of projects using Java, Spring, and Hibernate. She has written three books. In her first book, Learning Modular Java Programming, the reader explores the power of modular programming to build applications with Java and Spring. Her second book, Learning Spring 5.0, explores building an application using the Spring 5.0 Framework with the latest modules, such as WebFlux for dealing with reactive programming. Her recent book, Reactive Programming with Java 9, explains how to build robust, asynchronous, and event-driven applications with ease.
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 Boot 2.0 Cookbook Second Edition
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Getting Started with Spring Boot
Introduction
Using a Spring Boot template and starter
How to do it...
How it works...
Creating a simple application
How to do it...
How it works...
Launching an application using Gradle
How to do it...
How it works...
Using the command-line runners
How to do it...
How it works...
Setting up a database connection
Getting ready
How to do it...
How it works...
Setting up a data repository service
How to do it...
How it works...
Scheduling executors
Getting ready
How to do it...
How it works...
Configuring Web Applications
Creating a basic RESTful application
How to do it...
How it works...
Creating Spring Data REST service
How to do it...
How it works...
Configuring custom servlet filters
How to do it...
How it works...
Configuring custom interceptors
How to do it...
How it works...
Configuring custom HttpMessageConverters
How to do it...
How it works...
Configuring custom PropertyEditors
How to do it...
How it works...
Configuring custom type formatters
How to do it...
How it works...
Web Framework Behavior Tuning
Introduction
Configuring route matching patterns
How to do it...
How it works...
Configuring custom static path mappings
How to do it...
How it works...
Tuning Tomcat via ServletWebServerFactory
How to do it...
How it works...
Choosing embedded servlet containers
How to do it...
How it works...
Adding custom connectors
Getting ready
How to do it...
How it works...
Writing Custom Spring Boot Starters
Introduction
Understanding Spring Boot autoconfiguration
How to do it...
How it works...
Creating a custom Spring Boot autoconfiguration starter
How to do it...
How it works...
Configuring custom conditional bean instantiations
How to do it...
How it works...
Using custom @Enable annotations to toggle configuration
How to do it...
How it works...
Application Testing
Introduction
Creating tests for MVC controllers
How to do it...
How it works...
Configuring a database schema and populating it
How to do it...
How it works...
Initializing the database with Spring JPA and Hibernate
Initializing the database with Spring JDBC
Creating tests using an in-memory database
How to do it...
How it works...
Creating tests using mock objects
How to do it...
How it works...
Creating a JPA component test
How to do it...
How it works...
Creating a WebMvc component test
How to do it...
How it works...
Writing tests using Cucumber
How to do it...
How it works...
Writing tests using Spock
How to do it...
How it works...
Application Packaging and Deployment
Introduction
Creating a Spring Boot executable JAR
How to do it...
How it works...
Creating Docker images
How to do it...
How it works...
Building self-executing binaries
Getting ready
How to do it...
How it works...
Spring Boot environment configuration, hierarchy, and precedence
How to do it...
How it works...
Adding a custom PropertySource to the environment using EnvironmentPostProcessor
How to do it...
How it works...
Externalizing an environmental configuration using property files
How to do it...
How it works...
Externalizing an environmental configuration using environment variables
How to do it...
How it works...
Externalizing an environmental configuration using Java system properties
How to do it...
How it works...
Externalizing an environmental config using JSON
How to do it...
How it works...
Setting up Consul
How to do it...
How it works...
Externalizing an environmental config using Consul and envconsul
Getting ready
How to do it...
How it works...
Health Monitoring and Data Visualization
Introduction
Writing custom health indicators
How to do it...
How it works...
Configuring management context
How to do it...
How it works...
Emitting metrics
Getting ready
How to do it...
How it works...
Monitoring Spring Boot via JMX
Getting ready
How to do it...
How it works...
Managing Spring Boot via SSHd Shell and writing custom remote Shell commands
How to do it...
How it works...
Integrating Micrometer metrics with Graphite
Getting ready
How to do it...
How it works...
Integrating Micrometer metrics with Dashing
Getting ready
How to do it...
How it works...
Spring Boot DevTools
Introduction
Adding Spring Boot DevTools to a project
How to do it...
How it works...
Configuring LiveReload
How to do it...
How it works...
Configuring dynamic application restart triggers
How to do it...
How it works...
Using Remote Update
How to do it...
How it works...
Spring Cloud
Introduction
Getting started with Spring Cloud
How to do it...
How it works...
Service discovery using Spring Cloud Consul
How to do it...
How it works...
Using Spring Cloud Netflix – Feign
How to do it...
How it works...
Service discovery using Spring Cloud Netflix – Eureka
How to do it...
How it works...
Using Spring Cloud Netflix – Hystrix
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
Spring Boot has a lot of starters that are already a part of the Spring Boot family. This chapter will provide you with an overview of http://start.spring.io/, available starter modules, and will also show you how to make a project Bootiful, as Josh Long likes to call it.
In this chapter, we will learn about the following topics:
Using a Spring Boot template and starter
Creating a simple application
Launching an application using Gradle
Using the command-line runners
Setting up a database connection
Setting up a data repository service
Scheduling executors
In the fast-paced world of today's software development, the speed of application creation and the need for rapid prototyping are becoming more and more important. If you are developing a software using a JVM language, Spring Boot is exactly the kind of framework that will give you the power combined with the flexibility that will enable you to produce high-quality software at a rapid pace. So, let's take a look at how Spring Boot can help you to make your application Bootiful.
Spring Boot comes with over 40 different starter modules, which provide ready-to-use integration libraries for many different frameworks, such as database connections that are both relational and NoSQL, web services, social network integration, monitoring libraries, logging, template rendering, and the list just keeps going on. While it is not practically feasible to cover every single one of these components, we will go over the important and popular ones to get an idea of the possibilities and the ease of application development that Spring Boot provides us with.
We will start by creating a basic simple project skeleton, and Spring Boot will help us achieve this:
Head over to
http://start.spring.io
Fill out a simple form with the details about our project
Click on
Generate Project alt +
a premade project skeleton will download; this is where we begin
You will see the Project Dependencies section, where we can choose the kind of functionalities that our application will perform: Will it connect to a database? Will it have a web interface? Do we plan to integrate with any of the social networks bake in operational support? and so on. By selecting the desired technologies, the appropriate starter libraries will be added automatically to the dependency list of our pregenerated project template.
Before we proceed with the generation of our project, let's go over what exactly a Spring Boot starter is and the benefits it provides us with.
Spring Boot aims to make it easy to get started with creating an application. Spring Boot starters are bootstrap libraries that contain a collection of all the relevant transitive dependencies that are needed to start a particular functionality. Each starter has a special file, which contains the list of all the provided dependencies Spring provides. Let's take a look at the following link for a spring-boot-starter-test definition as an example:
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-starters/spring-boot-starter-test/src/main/resources/META-INF/spring.provides
Here we will see the following code:
provides: spring-test, spring-boot, junit, mockito, hamcrest-library, jsonassert, json-path
This tells us that by including spring-boot-starter-test in our build as a dependency, we will automatically get spring-test, spring-boot, junit, mockito, hamcrest-library,jsonassert, and json-path. These libraries will provide us with all the necessary things in order to start writing application tests for the software that we will develop, without needing to manually add these dependencies to the build file individually.
With more than 100 starters provided, and with the ongoing community additions increasing the list, it is very likely that unless, we find ourselves with the need to integrate with a fairly common or popular framework, there is already a starter out there that we can use.
The following table shows you the most notable ones so as to give you an idea of what is available:
Starter
Description
spring-boot-starter
This is the core Spring Boot starter that provides you with all the foundational functionalities. It is depended upon by all other starters, so no need to declare it explicitly.
spring-boot-starter-actuator
This starter provides you with a functionality to monitor, manage an application, and audit.
spring-boot-starter-jdbc
This starter provides you with a support to connect and use JDBC databases, connection pools, and so on.
spring-boot-starter-data-jpa
spring-boot-starter-data-*
The JPA starter provides you with needed libraries so you can use Java Persistence API (JPA): Hibernate, and others.
Various data-* family starters provide support for a number of datastores, such as MongoDB, Data REST, or Solr.
spring-boot-starter-security
This brings in all the needed dependencies for Spring Security.
spring-boot-starter-social-*
This allows you to integrate with Facebook, Twitter, and LinkedIn.
spring-boot-starter-test
This is a starter that contains the dependencies for spring-test and assorted testing frameworks: JUnit and Mockito, among others.
spring-boot-starter-web
This gives you all the needed dependencies for web application development. It can be enhanced with spring-boot-starter-hateoas, spring-boot-starter-websocket, spring-boot-starter-mobile, or spring-boot-starter-ws, and assorted template-rendering starters: sping-boot-starter-thymeleaf or spring-boot-starter-mustache.
spring-cloud-starter-*
Various cloud-* family starters providing support for a number of frameworks, such as Netflix OSS, Consul, or AWS.
Now that we have a basic idea of the starters that are available to us, let's go ahead and create our application template at http://start.spring.io.
The application that we are going to create is a book catalog management system. It will keep a record of books that were published, who the authors were, the reviewers, publishing houses, and so forth. We will name our project BookPub, and apply the following steps:
First let's switch to the full version by clicking the link below the
Generate Project alt +
button
Choose
Gradle Project
at the top
Use
Spring Boot
version
2.0.0(SNAPSHOT)
Use the default proposed
Group
name:
com.example
Enter
bookpub
for an
Artifact
field
Provide
BookPub
as a
Name
for the application
Specify
com.example.bookpub
as our
Package Name
Select
Jar
as
Packaging
Use
Java Version
as
8
Select the
H2
,
JDBC
, and
JPA
starters from the
Search for dependencies
selection so that we can get the needed artifacts in our
build
file to connect to an H2 database
Click on
Generate Project alt +
to download the project archive
Typically, the very first step of creating any application is to have a basic startable skeleton. As the Spring Boot starter has created the application template for us already, all we have to do is extract the code, build, and execute it. Now let's go to the console and launch the application with Gradle.
Change the location of our directory to where the bookpub.zip archive was extracted from and execute the following command from the command line:
$ ./gradlew clean bootRun
The output of the preceding command will be as follows:
...
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _
( ( )___ | '_ | '_| | '_ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |___, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
2017-12-16 23:18:53.721 : Starting BookPubApplication on mbp with PID 43850
2017-12-16 23:18:53.781 : Refreshing org.springframework.context. annotation.Annotatio
2017-12-16 23:18:55.544 : Building JPA container EntityManagerFactory for persistence
2017-12-16 23:18:55.565 : HHH000204: Processing PersistenceUnitInfo [name: default
2017-12-16 23:18:55.624 : HHH000412: Hibernate Core {5.2.12.Final}
2017-12-16 23:18:55.625 : HHH000206: hibernate.properties not found
2017-12-16 23:18:55.627 : HHH000021: Bytecode provider name : javassist
2017-12-16 23:18:55.774 : HCANN000001: Hibernate Commons Annotations {5.0.1.Final
2017-12-16 23:18:55.850 : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-12-16 23:18:55.902 : HHH000397: Using ASTQueryTranslatorFactory
2017-12-16 23:18:56.094 : HHH000227: Running hbm2ddl schema export
2017-12-16 23:18:56.096 : HHH000230: Schema export complete
2017-12-16 23:18:56.337 : Registering beans for JMX exposure on startup
2017-12-16 23:18:56.345 : Started BookPubApplication in 3.024 seconds (JVM running...
2017-12-16 23:18:56.346 : Closing org.springframework.context.annotation.AnnotationC..
2017-12-16 23:18:56.347 : Unregistering JMX-exposed beans on shutdown
2017-12-16 23:18:56.349 : Closing JPA EntityManagerFactory for persistence unit 'def...
2017-12-16 23:18:56.349 : HHH000227: Running hbm2ddl schema export
2017-12-16 23:18:56.350 : HHH000230: Schema export complete
BUILD SUCCESSFUL
Total time: 52.323 secs
As we can see, the application started just fine, but as we didn't add any functionality or configure any services, it existed straight away. From the startup log, however, we do see that the autoconfiguration did take place. Let's take a look at the following lines:
Building JPA container EntityManagerFactory for persistence unit 'default'
HHH000412: Hibernate Core {5.2.12.Final}
HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
This information tells us that, because we added the jdbc and data-jpa starters, the JPA container was created and will use Hibernate 5.2.12.Final to manage the persistence using H2Dialect. This was possible because we had the right classes in the classpath.
With our basic application skeleton ready, let's add some meat to the bones by making our application do something.
Let's start by first creating a class named StartupRunner. This will implement the CommandLineRunner interface, which basically provides just one method: public void run(String... args) --that will get called by Spring Boot only once after the application has started.
If we run our application again, by executing $ ./gradlew clean bootRun, we will get an output that is similar to the previous one. However, we will see our Hello message in the logs as well, which is as follows:
2017-12-16 21:57:51.048 INFO --- com.example.bookpub.StartupRunner : Hello
Even though the program will get terminated on execution, at least we made it do something!
Command-line runners are a useful functionality to execute the various types of code that only have to be run once, after startup. Some also use this as a place to start various executor threads, but Spring Boot provides a better solution for this task, which will be discussed at the end of this chapter. The command-line runner interface is used by Spring Boot to scan all of its implementations and invoke each instance's run method with the startup arguments. We can also use an @Order annotation or implement an Ordered interface so as to define the exact order in which we want Spring Boot to execute them. For example, Spring Batch relies on the runners to trigger the execution of the jobs.
As the command-line runners are instantiated and executed after the application has started, we can use the dependency injection to our advantage to wire in whatever dependencies we need, such as datasources, services, and other components. These can be utilized later while implementing run.
In every application, there is a need to access some data and conduct some operations on it. Most frequently, this source of data is a datastore of some kind, namely a database. Spring Boot makes it very easy to get started in order to connect to the database and start consuming the data via the JPA, among others.
Even though, by default, Spring Boot makes certain assumptions about the database configuration by examining the classpath for the presence of supported database drivers, it provides you with easy configuration options to tweak the database access via a set of exposed properties grouped under spring.datasource.
The things that we can configure are url, username, password, driver-class-name, and so on. If you want to consume the datasource from a JNDI location, where an outside container creates it, you can configure this using the spring.datasource.jndi-name property. The complete set of possible properties is fairly large, so we will not go into all of them. However, we will cover more options in Chapter 5, Application Testing, where we will talk about mocking data for application tests using a database.
If you want to connect to a regular (non-embedded) database, besides just having the appropriate driver library in the classpath, we need to specify the driver of our choice in the configuration. The following code snippet is what the configuration to connect to MySQL would resemble:
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.url: jdbc:mysql://localhost:3306/springbootcookbook
spring.datasource.username: root
spring.datasource.password:
If we wanted Hibernate to create the schema automatically, based on our entity classes, we would need to add the following line to the configuration:
spring.jpa.hibernate.ddl-auto=create-drop
You can go even further in the abstraction layer and, instead of autowiring a DataSource object, you could go straight for JdbcTemplate. This would instruct Spring Boot to automatically create a DataSource and then create a JdbcTemplate wrapping the datasource, thus providing you with a more convenient way of interacting with a database in a safe way. The code for JdbcTemplate is as follows:
@Autowired private JdbcTemplate jdbcTemplate;
You can also look in the spring-boot-autoconfigure source at an org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration file to see the code behind the datasource creation magic.
Connecting to a database and then executing good old SQL, though simplistic and straightforward, is not the most convenient way to operate on the data, map it in a set of domain objects, and manipulate the relational content. This is why multiple frameworks emerged to aid you with mapping the data from tables to objects, better known as object-relational mapping (ORM). The most notable example of such a framework is Hibernate.
In the previous example, we covered how to set up a connection to a database and configure the settings for the username and password, and we also discussed which driver to use, and so on. In this recipe, we will enhance our application by adding a few entity objects that define the structure of the data in the database and a CrudRepository interface to access the data.
As our application is a book-tracking catalogue, the obvious domain objects would be Book, Author, Reviewers, and Publisher.
Create a new package folder named
entity
under the
src/main/java/com/example/bookpub
directory from the root of our project.
In this newly created package, create a new class named
Book
with the following content:
