Learning Spring Boot 3.0 - Greg L. Turnquist - E-Book

Learning Spring Boot 3.0 E-Book

Greg L. Turnquist

0,0
29,99 €

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

Mehr erfahren.
Beschreibung

Spring Boot 3 brings more than just the powerful ability to build secure web apps on top of a rock-solid database. It delivers new options for testing, deployment, Docker support, and native images for GraalVM, along with ways to squeeze out more efficient usage of existing resources.
This third edition of the bestseller starts off by helping you build a simple app, and then shows you how to secure, test, bundle, and deploy it to production. Next, you’ll familiarize yourself with the ability to go “native” and release using GraalVM. As you advance, you’ll explore reactive programming and get a taste of scalable web controllers and data operations. The book goes into detail about GraalVM native images and deployment, teaching you how to secure your application using both routes and method-based rules and enabling you to apply the lessons you’ve learned to any problem. If you want to gain a thorough understanding of building robust applications using the core functionality of Spring Boot, then this is the book for you.
By the end of this Spring Boot book, you’ll be able to build an entire suite of web applications using Spring Boot and deploy them to any platform you need.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 341

Veröffentlichungsjahr: 2022

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



Learning Spring Boot 3.0

Third Edition

Simplify the development of production-grade applications using Java and Spring

Greg L. Turnquist

BIRMINGHAM—MUMBAI

Learning Spring Boot 3.0

Third Edition

Copyright © 2022 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(s), 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.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Bhavya Rao

Senior Editor: Mark D’Souza

Technical Editor: Simran Ali

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Nilesh Mohite

Marketing Coordinator: Anamika Singh

First published: November 2014

Second Edition: November 2017

Third Edition: December 2022

Production reference: 2130123

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-330-7

www.packt.com

To my fans on YouTube, who have given me the opportunity to share my love for Spring Boot. To my children, who have put up with me spending hours filming in my studio space. And to my wife, who has supported me in word and action as I’ve attempted to build a community.

– Greg L. Turnquist

Forewords

Spring Boot has been such a success that it’s probably not wrong to describe it as “mainstream” in 2022. Practically every Java developer will know something about it, and many, maybe even the majority, will have used it, even if in anger. But in software engineering, there’s always something new to learn, and there are always new problems to solve – that’s what makes it so rewarding in the end. There’s always something new to invent, too, and having the skill and opportunity to create code is extremely rewarding intellectually and in other ways.

One of the goals of Spring Boot is shared by the author of this book, and that is to get your ideas down into code as quickly and efficiently as possible, so you can get it to the most special place: Production. I wish you a short and pleasant journey, or maybe a long series of short and pleasant journeys.

In this book, Greg has used his insider advantage to add Spring Boot knowledge to some old, well-seasoned favourite problems that you all will have experienced as Java developers. What better way to learn than to look at Spring Boot through the lens of tasks that we all have to solve nearly every day: creating HTTP endpoints, securing them, connecting to databases, writing tests? This book adds some new angles to these old chestnuts by applying some modern ideas and tools, so read it and you will learn about things such as hypermedia and OAuth, all from the most practical and pragmatic of standpoints. It also starts right at the very beginning, and assumes no prior knowledge of Spring, or even Java. Anyone with some basic technical or programming skills will be able to get to grips with how and why to use Spring Boot.

There is more to Spring Boot than just main methods, embedded containers, autoconfiguration, and management endpoints. The pure joy of getting started with a fully featured Spring application in a few lines of code cannot be understated, for instance. I invite you to dip into this book, break out an editor or an IDE, and crank up some applications for yourself.

Greg has been an important member of the Spring Boot team, despite having a day job doing other things in the Spring Engineering effort, and we can be grateful for that, as well as the effort he has lavished on this excellent book. He has always been an educator and an informer, as well as an engineer, and this shows very clearly in this book. When I read it, I can hear Greg’s voice and personality very clearly, and it is always calm but enthusiastic, with a touch of humour. Read it yourself and enjoy – coding with Spring is still fun after all these years!

Dave Syer

Sr. Staff Engineer and Co-Creator of Spring Boot

London, 2022

I’ve known Greg Turnquist for a number of years. After I joined Pivotal (and before I had officially started) I first met him in person at SpringOne2GX, the annual conference of all things Spring and more (anyone remember the heady days of Groovy and Grails?). We had some great, thought-provoking conversations there, and they’ve continued through the years since.

One of the first Spring Boot books I read was Greg’s first edition of Learning Spring Boot. I wish I had read it sooner! I found myself recommending it to numerous people, along with other books by trusted colleagues, as a valuable introduction and reference to various Boot-related topics.

As an author myself, I know all too well the exhilarating and excruciating task Greg faced when writing and updating this book. Every author has to balance all the things they want to share, all the topics they feel most important, with the constant constraints of time and volume. Greg deftly threads this needle, providing a good foundation and then quickly shifting to topics important to developers, using Spring Boot to field real applications. Data? Security? Configuration? Integration with JavaScript? It’s in there.

I loved working with Greg on the Spring team, and I continue to enjoy every conversation we have. There will always be an honored place on my (virtual) mantle for Greg’s books, and I hope that you make room on yours for them as well. Read this book and get to know Greg! Your Spring Boot apps will benefit from both.

Best to you in your Spring Boot journey,

Mark Heckler

Principle Cloud Advocate, Microsoft

@mkheck

Look, I know you’re probably reading this foreword hoping for some compelling testimonial about this book, along with some witticism and a fun anecdote about life. Why wouldn’t you? It’s a preface to a book. But I can’t in good conscience write that foreword for you; it smacks of absurdity. But, of course, this book is fantastic. So, I don’t want to linger on the obvious.

Let’s talk about Greg, the author of this chef-d’oeuvre. Greg’s been on the Spring team longer than I have been. He’s forgotten more than most people will ever know about the depths of Spring. He invests time in the big and the small. You can trust him to be your sherpa and guide you from beginner to Spring Boot-iful. I do.

Greg’s a friend. He and I get along because, in some crucial ways, we’re very much alike. I like odd little projects that, while not necessarily mainstream, sometimes solve acutely painful problems. I once gave a talk to three people. My presentation was so specific that, out of thousands of attendees at the show, only three could be bothered to attend. I’m willing to advocate for the faintest glimmer of a solution if I believe in it. Greg is too. He invests in the big and small.

We both love the JVM and Python. That shared affection brings us around to Spring Python. Long ago, Greg brought some of the brilliance of the Spring Framework to the Python ecosystem with his project Spring Python. Python’s ecosystem brims with alternatives for every use case. In this sea of choice, Spring Python stood out. It delivered on the lofty goals of the Spring Framework while remaining “Pythonic”, a quality that signals a library will feel idiomatic to a familiar Python programmer. It showed a deep commitment to, and familiarity with, two vastly divergent ecosystems. I love Greg because of Spring Python. It shows he’s willing to sit down, roll up his sleeves, expand his horizons, and write code until a problem is solved– no matter how big or small. That willingness to dive deep into a topic makes him a gifted writer and teacher, which is evident in his books, courses, blogs, and articles. His gift makes these printed pages something more than yet another book on software; they’re a tome worth your time.

This book covers the just-released Spring Boot 3.0, arguably the most critical release of Spring Boot (or any other Spring ecosystem project) since Spring Boot itself appeared publicly for the very first time in 2013. I know all of us on the Spring team, Greg included, worked harder and longer than ever to get this release out the door. Yet, against all that work, Greg managed to get this book in your hands in record time. He did that so we, dear readers, could get to production in record time. He did that so we would not have to invest in the big and the small.

Josh Long

Spring Developer Advocate, VMware, (and well-known Greg Turnquist fan)

@starbuxman

Contributors

About the author

Greg L. Turnquist is the lead developer for Spring Data JPA and Spring Web Services. He has contributed to Spring HATEOAS, Spring Data REST, Spring Security, the Spring Framework, and many other parts of the Spring portfolio. He has maintained the Spring Data team’s CI system for years with his script-fu. He has written multiple tomes on Spring Boot, including Packt’s best-selling title Learning Spring Boot 2.0 Second Edition as well as the very first Spring Boot book to ever hit the market. He even launched his own YouTube channel, Spring Boot Learning (http://bit.ly/3uSPLCz), the channel where you learn about Spring Boot and have fun doing it. Before joining the Spring team, Greg worked as a senior software engineer at Harris Corp. on multiple projects including its ambitious $1.5 billion telecom contract with the FAA to build a nationwide, always-on network. As a test-bitten script junky, Greg is no stranger to midnight failures. He has a master’s degree in computer engineering and lives in the United States with his wife and their gaggle of minions.

I want to thank the Spring team, who have encouraged me at every turn, Dan Vega, for giving me the inspiration to make YouTube content, and the team at Packt, who have worked tirelessly to help me publish this technical work.

About the reviewer

Harsh Mishra is a software engineer who enjoys learning new technologies for his own knowledge and experience, focusing on designing and developing enterprise solutions. He is a clean code and Agile fan. He has been developing code for financial businesses since 2014 and has been using Java as his primary programming language. He also has product experience in Spring, Microsoft, GCP, DevOps, and other enterprise technologies.

Table of Contents

Preface

Part 1: The Basics of Spring Boot

1

Core Features of Spring Boot

Technical requirements

Installing Java 17

Installing a modern IDE

Creating a GitHub account

Finding additional support

Autoconfiguring Spring beans

Understanding application context

Exploring autoconfiguration policies in Spring Boot

Adding portfolio components using Spring Boot starters

Customizing the setup with configuration properties

Creating custom properties

Externalizing application configuration

Configuring property-based beans

Managing application dependencies

Summary

Part 2: Creating an Application with Spring Boot

2

Creating a Web Application with Spring Boot

Using start.spring.io to build apps

Creating a Spring MVC web controller

Using start.spring.io to augment an existing project

Leveraging templates to create content

Adding demo data to a template

Building our app with a better design

Injecting dependencies through constructor calls

Changing the data through HTML forms

Creating JSON-based APIs

Hooking in Node.js to a Spring Boot web app

Bundling JavaScript with Node.js

Creating a React.js app

Summary

3

Querying for Data with Spring Boot

Adding Spring Data to an existing Spring Boot application

Using Spring Data to easily manage data

Adding Spring Data JPA to our project

DTOs, entities, and POJOs, oh my!

Entities

DTOs

POJOs

Creating a Spring Data repository

Using custom finders

Sorting the results

Limiting query results

Using Query By Example to find tricky answers

Using custom JPA

Summary

4

Securing an Application with Spring Boot

Adding Spring Security to our project

Creating our own users with a custom security policy

Swapping hardcoded users with a Spring Data-backed set of users

Securing web routes and HTTP verbs

To CSRF or not to CSRF, that is the question

Securing Spring Data methods

Updating our model

Taking ownership of data

Adding a delete button

Locking down access to the owner of the data

Enabling method-level security

Displaying user details on the site

Leveraging Google to authenticate users

Pros of using OAuth

Cons of using OAuth

Creating a Google OAuth 2.0 application

Adding OAuth Client to a Spring Boot project

Invoking an OAuth2 API remotely

Creating an OAuth2-powered web app

Summary

5

Testing with Spring Boot

Adding JUnit 5 to the application

Creating tests for your domain objects

Testing web controllers with MockMVC

Testing data repositories with mocks

Testing data repositories with embedded databases

Adding Testcontainers to the application

Testing data repositories with Testcontainers

Testing security policies with Spring Security Test

Summary

Part 3: Releasing an Application with Spring Boot

6

Configuring an Application with Spring Boot

Creating custom properties

Creating profile-based property files

Switching to YAML

Setting properties with environment variables

Ordering property overrides

Summary

7

Releasing an Application with Spring Boot

Creating an uber JAR

Baking a Docker container

Building the “right” type of container

Releasing your application to Docker Hub

Tweaking things in production

Scaling with Spring Boot

Summary

8

Going Native with Spring Boot

What is GraalVM and why do we care?

Retrofitting our application for GraalVM

Running our native Spring Boot application inside GraalVM

Why do we want GraalVM again?

Baking a Docker container with GraalVM

Spring Boot 3.0 versus Spring Boot 2.7 and Spring Native

GraalVM and other libraries

Summary

Part 4: Scaling an Application with Spring Boot

9

Writing Reactive Web Controllers

What is reactive and why do we care?

Introduction to Reactive

Reactive Stream details

Creating a reactive Spring Boot application

Serving data with a reactive GET method

Consuming incoming data with a reactive POST method

Scaling applications with Project Reactor

Quick history on Java concurrent programming

Serving a reactive template

Creating a reactive web controller

Crafting a Thymeleaf template

Creating hypermedia reactively

Summary

10

Working with Data Reactively

Learning what it means to fetch data reactively

Picking a reactive data store

Creating a reactive data repository

Trying out R2DBC

Loading data with R2dbcEntityTemplate

Returning data reactively to an API controller

Reactively dealing with data in a template

Summary

Index

Other Books You May Enjoy

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803233307

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: The Basics of Spring Boot

Spring Boot has several key ingredients that underpin all of its features. You will learn how autoconfiguration, Spring Boot starters, configuration properties, and managed dependencies make it possible to build your most powerful application yet.

This part includes the following chapter:

Chapter 1, Core Features of Spring Boot

1

Core Features of Spring Boot

Rod Johnson, CEO of the company behind the foundation of the Spring Framework and dubbed the father of Spring, opened the 2008 Spring Experience conference with a stated mission: reducing Java complexity. The YouTube video titled Story time with Keith Donald Co-Founder SpringSource & Founder SteadyTown 2-27-2014 (https://springbootlearning.com/origin-of-spring), uploaded by TrepHub, is a 90-minute journey back into the early days of Spring guided by Keith Donald, one of Spring’s co-founders. Here too, you’ll find the same mission reinforced.

Java in the mid-2000s was challenging to use, difficult to test, and frankly short on enthusiasm.

But along came a toolkit: the Spring Framework. This toolkit focused on easing developers’ lives. And the excitement was off the charts. The buzz when I attended that 2008 conference was incredible.

Fast forward to 2013 at the SpringOne 2GX conference, the Spring team unveiled Spring Boot: a new approach to writing Spring apps. This approach resulted in standing-room attendance. I was in the room when co-leads Phil Webb and Dave Syer gave their first talk. In a room designed like a stadium lecture hall, the seats were packed. The opening keynote revealed a revolutionary way to build more extensive and powerful apps… with less.

This ability to do more with less using Spring Boot is what we’ll discover together as we journey into the world of the third generation of Spring Boot.

In this chapter, we’ll learn about the core features of Spring Boot, which show fundamentally how it does less with more. This is to get a taste of how Spring Boot operates, allowing us to leverage it in later chapters as we build applications. The key aspects that make Spring Boot powerful while retaining its flexibility to serve user needs will be described in this chapter.

In this chapter, we’ll cover the following topics:

Autoconfiguring Spring beansAdding components of the Spring portfolio using Spring Boot startersCustomizing the setup with configuration propertiesManaging application dependencies

Technical requirements

For this book, you’ll only need a handful of tools to follow along:

Java 17 Development Kit (JDK 17)A modern integrated development environment (IDE)A GitHub accountAdditional support

Installing Java 17

Spring Boot 3.0 is built on top of Java 17. For ease of installation and using Java, it’s easiest to use sdkman as your tool to handle installing and switching between different JDKs, as shown here:

Visit https://sdkman.io/.Following the site’s instructions, execute curl -s "https://get.sdkman.io" | bash from any terminal or shell on your machine.Follow any subsequent instructions provided.From there, install Java 17 on your machine by typing sdk install java 17.0.2-tem. When prompted, pick it as your default JDK of choice in any terminal.

This will download and install the Eclipse Temurin flavor of Java 17 (formerly known as AdoptOpenJDK). Eclipse Temurin is a free, open source version of OpenJDK, compliant with all standard Java TCKs. In general, it’s a variant of Java recognized by all parties as acceptable for Java development. Additionally, it comes with no requirements to pay for licensing.

Tip

If you need a commercially supported version of Java, then you will have to do more research. Many shops that provide commercial support in the Java space will have various options. Use what works best for you. But if commercial support is not needed, then Eclipse Temurin will work fine. It’s used by many projects managed by the Spring team itself.

Installing a modern IDE

Most developers today use one of the many free IDEs to do their development work. Consider these options:

IntelliJ IDEA – Community Edition (https://www.jetbrains.com/idea/)Spring Tools 4 (https://spring.io/tools):Spring Tools 4 for EclipseSpring Tools 4 for VS Code

IntelliJ IDEA is a powerful IDE. The Community Edition, which is free, has many bits that will serve you well. The Ultimate Edition, which costs 499 USD, is a complete package. If you grab this (or convince your company to buy a license!), it’s a valuable investment.

That being said, Spring Tools 4, whether you pick the Eclipse flavor or the VS Code one, is a powerful combo as well.

If you’re not sure, go ahead and test out each one, perhaps for a month, and see which one provides you with the best features. They each have top-notch support for Spring Boot.

At the end of the day, some people do prefer a plain old text editor. If that’s you, fine. At least evaluate these IDEs to understand the tradeoffs.

Creating a GitHub account

I always tell anyone entering the world of 21st century software development to open a GitHub account if they haven’t already. It will ease access to so many tools and systems out there.

Visit https://github.com/join if you’re just getting started.

This book’s code is hosted on GitHub at https://github.com/PacktPublishing/Learning-Spring-Boot-3.0.

You can work your way through the code presented in this book, but if you need to go to the source, visit the aforementioned link and grab a copy for yourself!

Finding additional support

Finally, there are some additional resources to visit for more help:

I host a YouTube channel focused on helping people get started with Spring Boot at https://youtube.com/@SpringBootLearning. All the videos and live streams there are completely free.There is additional content provided to my exclusive members at https://springbootlearning.com/member. My members also get one-on-one access to me with questions and concerns.If you’re a paying subscriber on Medium, I also write technical articles based on Spring Boot, along with overall software development topics, at https://springbootlearning.medium.com. Follow me over there.I also share any technical articles posted with my newsletter at https://springbootlearning.com/join for free. You also get an e-book for free if you sign up.

If you’ve downloaded Java 17 and installed an IDE, then you’re all set, so let’s get to it!

Autoconfiguring Spring beans

Spring Boot comes with many features. But the most well-known one, by far, is autoconfiguration.

In essence, when a Spring Boot application starts up, it examines many parts of our application, including classpath. Based on what the application sees, it automatically adds additional Spring beans to the application context.

Understanding application context

If you’re new to Spring, then it’s important to understand what we’re talking about when you hear application context.

Whenever a Spring Framework application starts up, whether or not Spring Boot is involved, it creates a container of sorts. Various Java beans that are registered with Spring Framework’s application context are known as Spring beans.

Tip

What’s a Java bean? Java beans are objects that follow a specific pattern: all the fields are private; they provide access to their fields through getters and setters, they have a no-argument constructor, and they implement the Serializable interface.

For example, an object of the Video type with name and location fields would set those two fields to private and offer getName(), getLocation(), setName(), and setLocation() as the ways to mutate the state of this bean. On top of that, it would have a no-argument Video() constructor call. It’s mostly a convention. Many tools provide property support by leveraging the getters and setters. The requirement to implement the Serializable interface, though, is not as tightly enforced.

Spring Framework has a deep-seated concept known as dependency injection (DI), where a Spring bean can express its need for a bean of some other type. For example, a BookRepository bean may require a DataSource bean:

@Bean public BookRepository bookRepository(DataSource dataSource) {   return new BookRepository(dataSource); }

This preceding Java configuration, when seen by the Spring Framework, will cause the following flow of actions:

bookRepository needs a DataSource.Ask the application context for a DataSource.The application context either has it or will go create one and return it.bookRepository executes its code while referencing the app context’s DataSource.BookRepository is registered in the application context under the name bookRepository.

The application context will ensure all Spring beans needed by the application are created and properly injected into each other. This is known as wiring.

Why all this instead of a handful of new operations in various class definitions? Simple. For the standard situation of powering up our app, all the beans are wired together as expected.

For a test case, it’s possible to override certain beans and switch to stubbed or mocked beans.

For cloud environments, it’s easy to find all DataSource and replace them with beans that link to bound data services.

By removing the new operation from our example BookRepository, and delegating that responsibility to the application context, we open the door to flexible options that make the whole life cycle of application development and maintenance much easier.

We’ll explore how Spring Boot heavily leverages the Spring Framework’s ability to inject beans based on various circumstances throughout this book. It is important to realize that Spring Boot doesn’t replace the Spring Framework but rather highly leverages it.

Now that you know what an application context is, it is time to dive into the many ways Spring Boot makes use of it through autoconfiguration.

Exploring autoconfiguration policies in Spring Boot

Spring Boot comes with a fistful of autoconfiguration policies. These are classes that contain @Bean definitions that are only registered based on certain conditional circumstances. Perhaps an example is in order?

If Spring Boot detects the class definition of DataSource somewhere on the classpath, a class found inside any Java Database Connectivity (JDBC) driver, it will activate its DataSourceAutoConfiguration. This policy will fashion some version of a DataSource bean. This is driven by the @ConditionalOnClass({ DataSource.class }) annotation found on that policy.

Inside DataSourceAutoConfiguration are inner classes, each driven by various factors. For example, some classes will discern whether or not we have used an embedded database such as H2 compared to a pooled JDBC asset such as HikariCP.

And just like that, the need for us to configure an H2 DataSource is removed. A small piece of infrastructure that is often the same across a multitude of applications is taken off our plate and instead managed by Spring Boot. And we can move more quickly toward writing business code that uses it.

Spring Boot autoconfiguration also has smart ordering built in, ensuring beans are added properly. Don’t worry! Using Spring Boot doesn’t depend on us having to know this level of detail.

Most of the time, we don’t have to know what Spring Boot is up to. It’s designed to do the right thing when various things are added to the build configuration.

The point is that many features, such as servlet handlers, view resolvers, data repositories, security filters, and more are activated, simply based on what dependencies we add to the build file.

And do you know what’s even better than automagically adding Spring beans? Backing off.

Some beans are created based on the classpath settings. But if a certain bean definition is detected inside our code, the autoconfiguration won’t kick in.

Continuing with the example from earlier, if we put something such as H2 in our classpath but define a DataSource bean and register it in the application context, Spring Boot will accept our DataSource bean over theirs.

No special hooks. No need to tell Spring Boot about it. Just create your own bean as you see fit, and Spring Boot will pick it up and run with it!

This may sound low-level, but Spring Boot’s autoconfiguration feature is transformational. If we focus on adding all the dependencies our project needs, Spring Boot will, as stated earlier, do what’s right.

Some of the autoconfiguration policies baked into Spring Boot extend across these areas:

Spring AMQP: Communicate asynchronously using an Advanced Message Queueing Protocol (AMQP) message brokerSpring AOP: Apply advice to code using Aspect-Oriented ProgrammingSpring Batch: Process large volumes of content using batched jobsSpring Cache: Ease the load on services by caching resultsData store connections (Apache Cassandra, Elasticsearch, Hazelcast, InfluxDB, JPA, MongoDB, Neo4j, Solr)Spring Data (Apache Cassandra, Couchbase, Elasticsearch, JDBC, JPA, LDAP, MongoDB, Neo4j, R2DBC, Redis, REST): Simplify data accessFlyway: Database schema managementTemplating engines (Freemarker, Groovy, Mustache, Thymeleaf)Serialization/deserialization (Gson and Jackson)Spring HATEOAS: Add Hypermedia as the Engine of Application State (HATEOAS) or hypermedia to web servicesSpring Integration: Support integration rulesSpring JDBC: Simplify accessing databases through JDBCSpring JMS: Asynchronous through Java Messaging Service (JMS)Spring JMX: Manage services through Java Management Extension (JMX)jOOQ: Query databases using Java Object Oriented Querying(jOOQ)Apache Kafka: Asynchronous messagingSpring LDAP: Directory-based services over Lightweight Directory Access Protocol (jOOQ)Liquibase: Database schema managementSpring Mail: Publish emailsNetty: An asynchronous web container (non-servlet-based)Quartz scheduling: Timed tasksSpring R2DBC: Access relational databases through Reactive Relational Database Connectivity (R2DBC)SendGrid: Publish emailsSpring Session: Web session managementSpring RSocket: Support for the async wire protocol known as RSocketSpring Validation: Bean validationSpring MVC: Spring’s workhorse for servlet-based web apps using the Model-View-Controller (MVC) paradigmSpring WebFlux: Spring’s reactive solution forweb appsSpring Web Services: Simple Object Access Protocol (SOAP)-based servicesSpring WebSocket: Support for the WebSocket messaging web protocol

This is a general list and is by no means exhaustive. It’s meant to give us a glance at the breadth of Spring Boot.

And as cool as this set of policies and its various beans are, it’s lacking a few things that would make it perfect. For example, can you imagine managing the versions of all those libraries? And what about hooking in our own settings and components? We’ll cover these aspects in the next few sections.

Adding portfolio components using Spring Boot starters

Remember in the previous section how we talked about adding H2? Or Spring MVC? Maybe Spring Security?

I’m going out on a limb here, but I’m presuming you don’t have any project dependency coordinates committed to memory. What does Spring Boot offer? A collection of virtual dependencies that will ease adding things to the build.

If you add org.springframework.boot:spring-boot-starter-web (as shown here) to the project, it will activate Spring MVC:

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId> </dependency>

If you add org.springframework.boot:spring-boot-starter-data-jpa to the project (as shown here), it will activate Spring Data JPA:

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

There are 50 different Spring Boot starters, each with the perfect coordinates to various bits of the Spring portfolio and other related third-party libraries.

But the problem isn’t just a shortcut to adding Spring MVC to classpath. There’s little difference between org.springframework.boot:spring-boot-starter-web and org.springframework:spring-webmvc. That’s something we probably could have figured out with our favorite internet search engine.

No, the issue is that if we want Spring MVC, it implies we probably want the whole Spring Web experience.

Note

Spring MVC versus Spring Web? Spring Framework has three artifacts involving web applications: Spring Web, Spring MVC, and Spring WebFlux. Spring MVC is servlet-specific bits. Spring WebFlux is for reactive web app development and is not tied to any servlet-based contracts. Spring Web contains common elements shared between Spring MVC and Spring WebFlux. This mostly includes the annotation-based programming model Spring MVC has had for years. This means that the day you want to start writing reactive web apps, you don’t have to learn a whole new paradigm to build web controllers.

If we added spring-boot-starter-web, this is what we’d need:

Spring MVC and the associated annotations found in Spring Web. These are the Spring Framework bits that support servlet-based web apps.Jackson Databind for serialization and deserialization (including JSR 310 support) to and from JSON.An embedded Apache Tomcat servlet container.Core Spring Boot starter.Spring Boot.Spring Boot Autoconfiguration.Spring Boot Logging.Jakarta annotations.Spring Framework Core.SnakeYAML to handle YAML Ain’t Markup Language (YAML)-based property files.

Note

What is Jakarta? Jakarta EE is the new official specification, replacing Java EE. Oracle wouldn’t relinquish its trademarked Java brand (nor grant a license) when it released its Java EE specs to the Eclipse Foundation. So, the Java community chose Jakarta as the new brand going forward. Jakarta EE 9+ is the official version that Spring Boot 3.0 supports. For more details, checkout my video What is Jakarta EE?at https://springbootlearning.com/jakarta-ee

This starter will bring in enough for you to build a real web application, not counting a templating engine. Now, we have autoconfiguration, which registers key beans in the application context. And we also have starters that simplify putting Spring portfolio components in classpath. But what’s missing is our ability to plug in customized settings, which we’ll tackle in the next section.

Customizing the setup with configuration properties

So, we’ve decided to pick up Spring Boot and we started adding some of its magical starters. As discussed earlier in this chapter, this will activate a handful of Spring beans.

Assuming we were building a web app and selected Spring MVC’s spring-boot-starter-web, it would activate embedded Apache Tomcat as the servlet container of choice. And with that, Spring Boot is forced to make a lot of assumptions.

For example, what port should it listen on? What about the context path? Secure Sockets Layer (SSL)? Threads? There are a dozen other parameters to fire up a Tomcat servlet container.

And Spring Boot will pick them. So, where does that leave us? Are we stuck with them? No.

Spring Boot introduces configuration properties as a way to plug property settings into any Spring bean. Spring Boot may load certain properties with default values, but we have the opportunity to override them.

The simplest example is the first property mentioned earlier in this section – the server port.

Spring Boot launches with a default port in mind, but we can change it. This can be done by first adding an application.properties file to our src/main/resources folder. Inside that file, we must merely add the following:

server.port=9000