Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Spring Boot 3.0
Learning Spring Boot 3.0

Learning Spring Boot 3.0: Simplify the development of production-grade applications using Java and Spring , Third Edition

Arrow left icon
Profile Icon Greg L. Turnquist
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (14 Ratings)
Paperback Dec 2022 270 pages 3rd Edition
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Greg L. Turnquist
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (14 Ratings)
Paperback Dec 2022 270 pages 3rd Edition
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Spring Boot 3.0

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:[email protected]: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:[email protected]: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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn Spring Boot in a cohesive manner with this practical guide by a core Spring contributor
  • Discover popular Java developer tools such as GraalVM native images, serving up JSON, and more
  • Build secure, scalable, and manageable web applications from zero to production

Description

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.

Who is this book for?

This book is for both novices and experienced Spring developers looking to learn how to build applications without wasting time on infrastructure and other tedious details. Working knowledge of the Java programming language is assumed.

What you will learn

  • Create powerful, production-grade web applications with minimal fuss
  • Support multiple environments with one artifact, and add production-grade support with features
  • Find out how to tweak your Java apps through different properties
  • Enhance the security model of your apps
  • Make use of enhancing features such as native deployment and reactive programming in Spring Boot
  • Build anything from lightweight unit tests to fully running embedded web container integration tests
  • Get a glimpse of reactive programming and decide if it's the right approach for you

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2022
Length: 270 pages
Edition : 3rd
Language : English
ISBN-13 : 9781803233307
Vendor :
VMware
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 30, 2022
Length: 270 pages
Edition : 3rd
Language : English
ISBN-13 : 9781803233307
Vendor :
VMware
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 139.97
Learning Spring Boot 3.0
€33.99
Spring Boot and Angular
€37.99
Solutions Architect's Handbook
€67.99
Total 139.97 Stars icon
Banner background image

Table of Contents

16 Chapters
Part 1: The Basics of Spring Boot Chevron down icon Chevron up icon
Chapter 1: Core Features of Spring Boot Chevron down icon Chevron up icon
Part 2: Creating an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 2: Creating a Web Application with Spring Boot Chevron down icon Chevron up icon
Chapter 3: Querying for Data with Spring Boot Chevron down icon Chevron up icon
Chapter 4: Securing an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 5: Testing with Spring Boot Chevron down icon Chevron up icon
Part 3: Releasing an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 6: Configuring an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 7: Releasing an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 8: Going Native with Spring Boot Chevron down icon Chevron up icon
Part 4: Scaling an Application with Spring Boot Chevron down icon Chevron up icon
Chapter 9: Writing Reactive Web Controllers Chevron down icon Chevron up icon
Chapter 10: Working with Data Reactively Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(14 Ratings)
5 star 57.1%
4 star 0%
3 star 0%
2 star 7.1%
1 star 35.7%
Filter icon Filter
Top Reviews

Filter reviews by




Pervaiz Dostiyar Jan 12, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is useful for anyone who has prior knowledge of Java, and anyone who is an experienced Spring developer and looking to learn how to build applications without wasting time on infrastructure and other tedious details. This book has all from basics of spring boot to Releasing an Application with Spring Boot and Reactively Working with Data.The author has covered spring boot application is diverse 10 chapters in this book, shows you how to leverage powerful databases and Spring Boot's highly adopted Spring MVC web technology with all the latest features of Spring Boot 3.I recommend buying this book 📚
Amazon Verified review Amazon
Nhat Quang Tram Feb 15, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have to say that I use Spring Boot a lot in my personal and professional career and this book is a good start to learn new concepts and update yourself with new features.
Amazon Verified review Amazon
Venkatesh Vemana Mar 26, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Those who are working with Java Spring Boot to develop applications . I highly recommend this Book. I just finished reading it is awesome and Thanks Greg, for this masterpiece.
Amazon Verified review Amazon
Gabriel J. Mar 10, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I think there is a misconception on what Spring and Spring Boot is. In order to get the essentials parts of this book you should know something about Spring. I think many people (including myself) started to learn Spring Boot first, instead of getting the basics of Spring and then moving to Spring Boot. In my point of view this is the wrong direction. If you are new to all of this, start with Spring, then move to learn Spring Boot.It's a good book. It's not dense and I could read it in less than 2 weeks. It worth notice it's not a bible of Spring Boot, so don't expect to see all the nitty gritty details about it. Also don't expect a full comprehensive material on Spring Security or Spring Data since they are very complex topics that deserve their own books.I consider it as a good resource to understand the whole picture, like the components available and their basic usage/integration/concept.This should not be the first book neither or will be the last book you will read in your Spring/Spring Boot career.
Amazon Verified review Amazon
Alazar Mar 03, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has everything you need to start your springboot journey and I like how each concept are well structured and written with attention of details!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.