Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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 Profile Icon Greg L. Turnquist
Arrow right icon
€33.99
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 Profile Icon Greg L. Turnquist
Arrow right icon
€33.99
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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
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: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.

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
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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

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
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela