Home Web Development Learning Spring Boot 3.0 - Third Edition

Learning Spring Boot 3.0 - Third Edition

By Greg L. Turnquist
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Core Features of Spring Boot
About this book
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.
Publication date:
December 2022
Publisher
Packt
Pages
270
ISBN
9781803233307

 

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 beans
  • Adding components of the Spring portfolio using Spring Boot starters
  • Customizing the setup with configuration properties
  • Managing 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 account
  • Additional 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:

  1. Visit https://sdkman.io/.
  2. Following the site’s instructions, execute curl -s "https://get.sdkman.io" | bash from any terminal or shell on your machine.
  3. Follow any subsequent instructions provided.
  4. 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 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:

  1. bookRepository needs a DataSource.
  2. Ask the application context for a DataSource.
  3. The application context either has it or will go create one and return it.
  4. bookRepository executes its code while referencing the app context’s DataSource.
  5. 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 broker
  • Spring AOP: Apply advice to code using Aspect-Oriented Programming
  • Spring Batch: Process large volumes of content using batched jobs
  • Spring Cache: Ease the load on services by caching results
  • Data 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 access
  • Flyway: Database schema management
  • Templating 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 services
  • Spring Integration: Support integration rules
  • Spring JDBC: Simplify accessing databases through JDBC
  • Spring 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 messaging
  • Spring LDAP: Directory-based services over Lightweight Directory Access Protocol (jOOQ)
  • Liquibase: Database schema management
  • Spring Mail: Publish emails
  • Netty: An asynchronous web container (non-servlet-based)
  • Quartz scheduling: Timed tasks
  • Spring R2DBC: Access relational databases through Reactive Relational Database Connectivity (R2DBC)
  • SendGrid: Publish emails
  • Spring Session: Web session management
  • Spring RSocket: Support for the async wire protocol known as RSocket
  • Spring Validation: Bean validation
  • Spring MVC: Spring’s workhorse for servlet-based web apps using the Model-View-Controller (MVC) paradigm
  • Spring WebFlux: Spring’s reactive solution for web apps
  • Spring Web Services: Simple Object Access Protocol (SOAP)-based services
  • Spring 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

This Java property file, a file format supported since the early days of Java 1.0, contains a list of key-value pairs separated by an equals sign (=). The left-hand side contains the key (server.port) and the right-hand side contains the value (9000).

When a Spring Boot application launches, it will look for this file and scan in all its property entries, and then apply them. And with that, Spring Boot will switch from its default port of 8080 to port 9000.

Note

The server port property is really handy when you need to run more than one Spring Boot-based web application on the same machine.

Spring Boot is not limited to the handful of properties that can be applied to embedded with Apache Tomcat. Spring Boot has alternative servlet container starters, including Jetty and Undertow. We’ll learn how to pick and choose servlet containers in Chapter 2, Creating a Web Application with Spring Boot.

What’s important is knowing that no matter which servlet container we use, the servlet.port property will be applied properly to switch the port the servlet will serve web requests on.

Perhaps you’re wondering why? Having a common port property between servlet containers eases choosing servlet containers.

Yes, there are container-specific property settings if we needed that level of control. But generalized properties make it easy for us to select our preferred container and move to a port and context path of choice.

But we’re getting ahead of ourselves. The point of Spring Boot property settings isn’t about servlet containers. It’s about creating opportunities to make our applications flexible at runtime. And the next section will show us how to create configuration properties.

Creating custom properties

At the beginning of this section, I mentioned that configuration properties can be applied to any Spring bean. This applies not just to Spring Boot’s autoconfigured beans, but to our own Spring beans!

Look at the following code:

@Component
@ConfigurationProperties(prefix = "my.app")
public class MyCustomProperties {
  // if you need a default value, assign it here or the 
     constructor
  private String header;
  private String footer;
  // getters and setters
}

The preceding code can be described as follows:

  • @Component is Spring Framework’s annotation to automatically create an instance of this class when the application starts and register it with the application context.
  • @ConfigurationProperties is a Spring Boot annotation that labels this Spring bean as a source of configuration properties. It indicates that the prefix of such properties will be my.app.

The class itself must adhere to standard Java bean property rules (described earlier in this chapter). It will create various fields and include proper getters and setters – in this case, getHeader() and getFooter().

With this class added to our application, we can include our own custom properties, as follows:

application.properties:
my.app.header=Learning Spring Boot 3
my.app.footer=Find all the source code at https://github.com/PacktPublishing/Learning-Spring-Boot-3.0

These two lines will be read by Spring Boot and injected into the MyCustomProperties Spring bean before it gets injected into the application context. We can then inject that bean into any relevant component in our app.

But a much more tangible concept would be including properties that should never be hardcoded into an application, as follows:

@Component
@ConfigurationProperties(prefix = "app.security")
public class ApplicationSecuritySettings {
  private String githubPersonalCode;
  public String getGithubPersonalCode() {
    return this.githubPersonalCode;
  }
  public void setGithubPersonalCode
    (String githubPersonalCode) {
      this.githubPersonalCode = githubPersonalCode;
  }
}

The preceding code is quite similar to the earlier code but with the following differences:

  • The prefix for this class’s properties is app.security
  • The githubPersonalCode field is a string used to store an API passcode used to presumably interact with GitHub through its OAuth API

An application that needs to interact with GitHub’s API will need a passcode to get in. We certainly do not want to bake that into the application. What if the passcode were to change? Should we rebuild and redeploy the whole application just for that?

No. It’s best to delegate certain aspects of an application to an external source. How can we do that? The next section will show how!

Externalizing application configuration

Did I mention an external source in the previous section? Yes. That’s because while you can put properties into an application.properties file that gets baked into the application, that isn’t the only way to do things. There are more options when it comes to providing Spring Boot with application properties that aren’t solely inside the deliverable.

Spring Boot not only looks for that application.properties tucked inside our JAR file upon startup. It will also look directly in the folder from where we run the application to find any application.properties files there and load them.

We can deliver our JAR file along with an application.properties file right beside it as an immediate way to override pre-baked properties (ours or Spring Boot’s!).

But wait, there’s more. Spring Boot also supports profiles.

What are profiles? We can create profile-specific property overrides. A good example would be one configuration for the development environment, but a different one for our test bed, or production.

In essence, we can create variations of application.properties, as shown here:

  • application-dev.properties is a set of properties applied when the dev profile is activated
  • application-test.properties is applied when the test profile is applied
  • application.properties is always applied, so it could be deemed the production environment

Perhaps an example is in order?

Imagine having our database connection details captured in a property named my.app.databaseUrl, as shown here:

application.properties:
my.app.databaseUrl=https://user:pass@production-server.com:1234/prod/

The test bed of our system surely won’t be linked to the same production server. So, instead, we must provide an application-test.properties with the following override:

application-test.properties:
my.app.databaseUrl=http://user:pass@test-server.com:1234/test/

To activate this override, simply include -Dspring.profiles.active=test as an extra argument to the Java command to run our app.

It’s left as an exercise for you to think up overrides for a development environment.

Note

Since production is the end state of an application, it’s usually best practice to let application.properties be the production version of property settings. Use other profiles for other environments or configurations.

Notice earlier how we said Spring Boot will scan either application.properties files embedded inside our JAR as well as outside the JAR? The same goes for profile-specific property files.

So far, we’ve mentioned internal and external properties, both default and profile-specific. In truth, there are many more ways to bind property settings into a Spring Boot application.

Several are included in this list, ordered from lowest priority to highest priority:

  • Default properties provided by Spring Boot’s SpringApplication.setDefaultProperties() method.
  • @PropertySource-annotated @Configuration classes.
  • Config data (such as application.properties files).
  • A RandomValuePropertySource that has properties only in random.*.
  • OS environment variables.
  • Java system properties (System.getProperties()).
  • JNDI attributes from java:comp/env.
  • ServletContext init parameters.
  • ServletConfig init parameters.
  • Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  • Command-line arguments.
  • The properties attribute on your tests. This is available with the @SpringBootTest annotation and also slice-based testing (which we’ll cover later in Chapter 5, Testing with Spring Boot).
  • @TestPropertySource annotations on your tests.
  • DevTools global settings properties (the $HOME/.config/spring-boot directory when Spring Boot DevTools is active).

Config files are considered in the following order:

  • Application properties packaged inside your JAR file.
  • Profile-specific application properties inside your JAR file.
  • Application profiles outside your JAR file.
  • Profile-specific application properties outside your JAR file.

It’s a bit of a tangent, but we can also ensure certain beans are only activated when certain profiles are activated.

And properties aren’t confined to injecting data values. The following section will show you how to make property-based beans.

Configuring property-based beans

Properties aren’t just for providing settings. They can also govern which beans are created and when.

The following code is a common pattern for defining beans:

@Bean 
@ConditionalOnProperty(prefix="my.app", name="video")
YouTubeService youTubeService() {
    return new YouTubeService();
}

The preceding code can be explained as follows:

  • @Bean is Spring’s annotation, signaling that the following code should be invoked when creating an application context and the created instance is added as a Spring bean
  • @ConditionalOnProperty is Spring Boot’s annotation to conditionalize this action based on the existence of the property

If we set my.app.video=youtube, then a bean of the YouTubeService type will be created and injected into the application context. Actually, in this scenario, if we define my.app.video with any value, it will create this bean.

If the property does not exist, then the bean won’t be created. This saves us from having to deal with profiles.

It’s possible to fine-tune this even further, as shown here:

@Bean 
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="youtube")
YouTubeService youTubeService() {
    return new YouTubeService();
}
@Bean 
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="vimeo")
VimeoService vimeoService() {
    return new VimeoService();
}

This preceding code can be explained as follows:

  • @Bean, like before, will define Spring beans to be created and added to the application context
  • @ConditionalOnProperty will conditionalize these beans to only be created if the named property has the stated values

This time, if we set my.app.video=youtube, a YouTubeService will be created. But if we were to set my.app.video=vimeo, a VimeoService bean would be created instead.

All of this presents a rich way to define application properties. We can create all the configuration beans we need. We can apply different overrides based on various environments. And we can also conditionalize which variants of various services are created based on these properties.

We can also control which property settings are applicable in a given environment, be it a test bed, a developer’s work environment, a production setting, or a backup facility. We can even apply additional settings based on being in different cloud providers!

And as a bonus, most modern IDEs (IntelliJ IDEA, Spring Tool Suite, Eclipse, and VS Code) offer autocompletion inside application.properties files! We will cover this in more detail throughout the rest of this book.

Now, the last thing we need to craft a powerful application is the means to maintain it. This will be covered in the next section.

 

Managing application dependencies

There’s a subtle thing we may have glossed over. It is best expressed in this simple question:

What version of Spring Framework works best with which version of Spring Data JPA and Spring Security?

Indeed, that is quite tricky. In fact, over the years, thousands of hours have probably been spent simply managing version dependencies.

Imagine that a new version of Spring Data JPA is released. It has an update to the Query by Example option you’ve been waiting for – the one where they finally handle domain objects that use Java’s Optional type in the getters. It’s been bugging you because anytime you had an Optional.EMPTY, it just blew up.

So, you’re eager to upgrade.

But you don’t know if you can. The last upgrade cost you a week of effort. It included digging through release reports for Spring Framework as well as Spring Data JPA.

Your system also uses Spring Integration and Spring MVC. If you bump up the version, will those other dependencies run into any issues?

With the miracle of autoconfiguration, all those slick starters and easy-to-use configuration properties can come off as a bit weak if you’re left dealing with this conundrum.

That’s why Spring Boot also comes loaded with an extensive list of 195 approved versions. If you pick a version of Spring Boot, the proper version of the Spring portfolio, along with some of the most popular third-party libraries, will already be selected.

There’s no need to deal with micromanaging dependency versions. Just bump up the version of Spring Boot and pick up all the improvements.

The Spring Boot team not only releases the software themselves. They also release a Maven bill of materials (BOM). This is a separate module known as Spring Boot Dependencies. Don’t panic! It’s baked into the modules that are picked up when you adopt Spring Boot.

And with that in place, you can easily pick up new features, bug patches, and any resolved security issues.

Important

It doesn’t matter if you’re using Maven or Gradle. Either build system can consume Spring Boot dependencies and apply their collection of managed dependencies.

We won’t go into how Spring Boot dependencies are configured in the build system. Just understand that you can choose the build system you prefer. How to apply this will be covered at the beginning of Chapter 2, Creating a Web Application with Spring Boot.

That last part is key, so I’ll repeat it: when Common Vulnerabilities and Exposures (CVE) security vulnerabilities are reported to the Spring team, no matter which component of the Spring portfolio is impacted, the Spring Boot team will make a security-based patch release.

This BOM is released alongside Spring Boot’s actual code. All we have to do is adjust the version of Spring Boot in our build file, and everything will follow.

To paraphrase Phil Webb, project lead for Spring Boot, if Spring Framework were a collection of ingredients, then Spring Boot would be a pre-baked cake.

 

Summary

In this chapter, we discovered the magic of Spring Boot and how it not only brings in Spring beans but also backs off in light of user code. We found out how Spring Boot starters make it easy to add various features of the Spring portfolio as well as some third-party libraries with some simple dependencies. We saw how Spring Boot leverages properties files, allowing us to override various settings of autoconfiguration. We also saw that we can even create our own properties. We learned that Spring Boot manages an entire suite of library dependencies, allowing us to delegate everything to the version of Spring Boot. We also saw how to override that on a one-off basis.

In the next chapter, we’ll discover how to apply the concepts from this chapter by building our very first Spring Boot 3 application, starting with the web layer. We’ll craft templates and JSON-based APIs, and even stir in a little JavaScript.

About the Author
  • Greg L. Turnquist

    Greg L. Turnquist works on the Spring team at VMware. He is a committer to Spring Data, Spring Boot, R2DBC, Spring HATEOAS, and other Spring projects. He has written the Hacking with Spring Boot series as well as Packt's best-selling title, Learning Spring Boot 2.0 2nd Edition. He co-founded the Nashville Java User Group in 2010 and hasn't met a Java app (yet) that he doesn't like. He completed his master's degree in computer engineering at Auburn University and lives in the United States with his family. Be sure to check out his YouTube channel, Spring Boot Learning, where you learn about Spring Boot and have fun doing it at springbootlearning.

    Browse publications by this author
Learning Spring Boot 3.0 - Third Edition
Unlock this book and the full library FREE for 7 days
Start now