Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
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!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Web Development> Server Side Web Development> Learning Spring Boot 3.0
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
€23.99€26.99
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.4(14 Ratings)
eBookDec 2022270 pages3rd Edition
eBook
€23.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
€23.99€26.99
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.4(14 Ratings)
eBookDec 2022270 pages3rd Edition
eBook
€23.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€23.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Learning Spring Boot 3.0

Core Features of Spring Boot

Rod Johnson, CEO of the company behind the foundation of theSpring Framework and dubbed thefather of Spring, opened the 2008 Spring Experience conference with a stated mission: reducing Java complexity. The YouTube video titledStory time with Keith Donald Co-Founder SpringSource & Founder SteadyTown 2-27-2014 (https://springbootlearning.com/origin-of-spring), uploaded byTrepHub, 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 samemission reinforced.

Java in the mid-2000s was challenging to use, difficult to test, and frankly shorton 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 conferencewas incredible.

Fast forward to 2013 at theSpringOne 2GX conference, the Spring team unveiledSpring 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 ofSpring 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 inthis chapter.

In this chapter, we’ll cover thefollowing topics:

  • AutoconfiguringSpring beans
  • Adding components of the Spring portfolio using SpringBoot starters
  • Customizing the setup withconfiguration properties
  • Managingapplication dependencies

Technical requirements

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

  • Java 17 Development Kit (JDK 17)
  • A modernintegrated developmentenvironment (IDE)
  • AGitHub 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 usesdkman as your tool to handle installing and switching between different JDKs, asshown here:

  1. Visithttps://sdkman.io/.
  2. Following the site’s instructions, executecurl -s "https://get.sdkman.io" | bash from any terminal or shell onyour machine.
  3. Follow any subsequentinstructions provided.
  4. From there, install Java 17 on your machine by typingsdk install java 17.0.2-tem. When prompted, pick it as your default JDK of choice inany terminal.

This will download and install theEclipse Temurin flavor of Java 17 (formerly known asAdoptOpenJDK). 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 payfor 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 Springteam itself.

Installing a modern IDE

Most developers today use one of the many free IDEs to do their development work. Considerthese 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 comboas 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 forSpring 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 understandthe 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 systemsout there.

Visithttps://github.com/join if you’re justgetting started.

This book’s code is hosted on GitHubathttps://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 copyfor yourself!

Finding additional support

Finally, there are some additional resources to visit formore 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 arecompletely free.
  • There is additional content provided to my exclusive members athttps://springbootlearning.com/member. My members also get one-on-one access to me with questionsand concerns.
  • If you’re a paying subscriber on Medium, I also write technical articles based on Spring Boot, along with overall software development topics, athttps://springbootlearning.medium.com. Follow meover there.
  • I also share any technical articles posted with my newsletter athttps://springbootlearning.com/join for free. You also get an e-book for free if yousign up.

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

Autoconfiguring Spring beans

Spring Boot comeswith 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, includingclasspath. Based on what the application sees, it automatically addsadditionalSpring beans to theapplication context.

Understanding application context

If you’re new to Spring, then it’s important to understand what we’re talking about when you hearapplication 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 asSpring beans.

Tip

What’s a Java bean? Java beansare 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 theSerializable interface.

For example, an object of theVideo type withname andlocation fields would set those two fields toprivate and offergetName(),getLocation(),setName(), andsetLocation() as the ways to mutate the state of this bean. On top of that, it would have a no-argumentVideo() constructor call. It’s mostly a convention. Many tools provide property support by leveraging the getters and setters. The requirement to implement theSerializable interface, though, is not astightly enforced.

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

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

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

  1. bookRepository needsaDataSource.
  2. Ask the application context foraDataSource.
  3. The application context either has it or will go create one andreturn it.
  4. bookRepository executes its code while referencing the appcontext’sDataSource.
  5. BookRepository is registered in the application context under thenamebookRepository.

The application context willensure all Spring beans needed by the application are created and properly injected into each other. This is knownaswiring.

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 togetheras expected.

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

For cloud environments, it’s easy to find allDataSource and replace them with beans that link to bounddata services.

By removing the new operation from our exampleBookRepository, 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 maintenancemuch 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 itthrough autoconfiguration.

Exploring autoconfiguration policies in Spring Boot

Spring Boot comes witha fistful of autoconfiguration policies. These areclasses that contain@Bean definitions that are only registered based on certain conditional circumstances. Perhaps an example isin order?

If Spring Boot detects the class definition ofDataSource somewhere on theclasspath, a class foundinside anyJava Database Connectivity (JDBC) driver, it will activate itsDataSourceAutoConfiguration. This policy will fashion some version of aDataSource bean. This is driven by the@ConditionalOnClass({ DataSource.class }) annotation found onthat policy.

InsideDataSourceAutoConfiguration are inner classes, each driven by various factors. For example, some classes will discern whether or not we have used an embedded database such asH2 compared to a pooled JDBC asset suchasHikariCP.

And just like that, theneed for us to configure an H2DataSource 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 thatuses it.

Spring Boot autoconfiguration also has smart ordering built in, ensuring beans are added properly. Don’t worry! UsingSpring Boot doesn’t depend on us having to know this levelof 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 thebuild 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 thebuild file.

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

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

Continuing with the example from earlier, if we put something such asH2 in ourclasspath but define aDataSource bean and register it in the application context, Spring Boot will accept ourDataSource beanover 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 runwith 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 acrossthese areas:

  • Spring AMQP: Communicate asynchronously using anAdvanced Message Queueing Protocol (AMQP)message broker
  • Spring AOP: Apply advice to code usingAspect-Oriented Programming
  • Spring Batch: Process large volumes of content usingbatched jobs
  • Spring Cache: Ease the load on services bycaching 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): Simplifydata access
  • Flyway: Databaseschema management
  • Templating engines (Freemarker, Groovy,Mustache, Thymeleaf)
  • Serialization/deserialization (Gsonand Jackson)
  • Spring HATEOAS: AddHypermedia as the Engine of Application State (HATEOAS) or hypermedia toweb services
  • Spring Integration: Supportintegration rules
  • Spring JDBC: Simplifyaccessing databasesthroughJDBC
  • Spring JMS: Asynchronous throughJava MessagingService (JMS)
  • Spring JMX: Manage services throughJava ManagementExtension (JMX)
  • jOOQ: Query databasesusingJava Object OrientedQuerying(jOOQ)
  • Apache Kafka:Asynchronous messaging
  • Spring LDAP: Directory-basedservices overLightweight Directory AccessProtocol (jOOQ)
  • Liquibase: Databaseschema management
  • Spring Mail:Publish emails
  • Netty: An asynchronous webcontainer (non-servlet-based)
  • Quartz scheduling:Timed tasks
  • Spring R2DBC: Access relational databases throughReactive Relational DatabaseConnectivity (R2DBC)
  • SendGrid:Publish emails
  • Spring Session: Websession management
  • Spring RSocket: Support for the async wire protocol knownas RSocket
  • Spring Validation:Bean validation
  • Spring MVC: Spring’s workhorse for servlet-based web apps using theModel-View-Controller (MVC) paradigm
  • Spring WebFlux: Spring’s reactive solution forweb apps
  • Spring Web Services:Simple Object Access Protocol (SOAP)-based services
  • Spring WebSocket: Support for the WebSocket messagingweb protocol

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

And as cool as this set ofpolicies 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 nextfew sections.

Adding portfolio components using Spring Boot starters

Remember in the previous section how we talkedabout adding H2? OrSpring MVC? MaybeSpring 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 tothe build.

If you addorg.springframework.boot:spring-boot-starter-web (as shown here) to the project, it will activateSpring MVC:

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

If you addorg.springframework.boot:spring-boot-starter-data-jpa to the project (as shown here), it will activate SpringData 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 relatedthird-party libraries.

But the problem isn’t just a shortcut to adding Spring MVC toclasspath. There’s little difference betweenorg.springframework.boot:spring-boot-starter-web andorg.springframework:spring-webmvc. That’s something we probably could have figured out with our favorite internetsearch engine.

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

Note

Spring MVC versusSpring 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 buildweb controllers.

If we addedspring-boot-starter-web, this is whatwe’d need:

  • Spring MVCand the associated annotations found in Spring Web. These are the Spring Framework bits thatsupport servlet-basedweb apps.
  • Jackson Databind for serialization and deserialization (including JSR 310 support) to andfrom JSON.
  • An embedded Apache Tomcatservlet container.
  • Core SpringBoot starter.
  • Spring Boot.
  • SpringBoot Autoconfiguration.
  • SpringBoot Logging.
  • Jakarta annotations.
  • SpringFramework Core.
  • SnakeYAMLto handleYAML Ain’t Markup Language (YAML)-basedproperty files.

Note

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

This starter will bring inenough 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 inclasspath. But what’s missing is our ability to plug in customized settings, which we’ll tackle in thenext section.

Customizing the setup with configuration properties

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

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

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

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

Spring Boot introducesconfiguration 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 tooverride them.

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

Spring Boot launches with a default port in mind, but we can change it. This can be done by first adding anapplication.properties file to oursrc/main/resources folder. Inside that file, we must merely addthe 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 thevalue (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 of8080 to port9000.

Note

The server port property is really handy when you need to run more than one Spring Boot-based web application on thesame 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, includingJetty andUndertow. We’ll learn how to pick and choose servlet containers inChapter 2,Creating a Web Application withSpring Boot.

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

Perhaps you’re wondering why? Having a common port property between servlet containers eases choosingservlet 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 pathof 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 createconfiguration properties.

Creating custom properties

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

Look at thefollowing 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 describedas follows:

  • @Component is Spring Framework’s annotation to automatically create an instance of this class when the application starts and register it with theapplication 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 willbemy.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()andgetFooter().

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

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

These two lines will be read by Spring Boot and injected into theMyCustomProperties Spring bean before it gets injected into the application context. We can then inject that bean into any relevant component inour 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 thefollowing differences:

  • The prefix for this class’s propertiesisapp.security
  • ThegithubPersonalCode field is a string used to store an API passcode used to presumably interact with GitHub through itsOAuth 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 justfor that?

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

Externalizing application configuration

Did I mention an external source in the previous section? Yes. That’s because while you can put properties into anapplication.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 insidethe deliverable.

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

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

But wait, there’s more. Spring Boot alsosupportsprofiles.

What are profiles? We can createprofile-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 ofapplication.properties, asshown here:

  • application-dev.properties is a set of properties applied when thedev profileis activated
  • application-test.properties is applied when thetest profileis applied
  • application.properties is always applied, so it could be deemed theproduction environment

Perhaps an example isin order?

Imagine having our database connection details captured in a property namedmy.app.databaseUrl, asshown 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 anapplication-test.properties with thefollowing override:

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

To activate thisoverride, simply include-Dspring.profiles.active=test as an extra argument to the Java command to runour app.

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

Note

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

Notice earlier how we said Spring Boot will scan eitherapplication.properties files embedded inside our JAR as well as outside the JAR? The same goes for profile-specificproperty 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 SpringBoot application.

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

  • Default properties provided by Spring Boot’sSpringApplication.setDefaultProperties() method.
  • @PropertySource-annotated@Configuration classes.
  • Config data (such asapplication.properties files).
  • ARandomValuePropertySource that has properties onlyinrandom.*.
  • OSenvironment variables.
  • Java systemproperties (System.getProperties()).
  • JNDI attributesfromjava:comp/env.
  • ServletContextinit parameters.
  • ServletConfiginit parameters.
  • Properties fromSPRING_APPLICATION_JSON (inline JSON embedded in an environment variable orsystem property).
  • Command-line arguments.
  • Theproperties attribute on your tests. This is available with the@SpringBootTest annotation and also slice-based testing (which we’ll cover later inChapter 5,Testing withSpring Boot).
  • @TestPropertySource annotations onyour tests.
  • DevTools global settings properties (the$HOME/.config/spring-boot directory when Spring Boot DevToolsis active).

Config files are considered in thefollowing order:

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

It’s a bit of a tangent, but we can also ensure certain beans areonly activated when certain profilesare activated.

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

Configuring property-based beans

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

The following code is a common pattern fordefining beans:

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

The preceding code can be explainedas 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 aSpring bean
  • @ConditionalOnProperty is Spring Boot’s annotation to conditionalize this action based on the existence ofthe property

If we setmy.app.video=youtube, then a bean of theYouTubeService type will be created and injected into the application context. Actually, in this scenario, if we definemy.app.video with any value, it will createthis bean.

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

It’s possible to fine-tune this even further, asshown 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 beexplainedas follows:

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

This time, if we setmy.app.video=youtube, aYouTubeService will be created. But if we were to setmy.app.video=vimeo, aVimeoService bean would becreated 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 onthese 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 differentcloud providers!

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

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

Managing application dependencies

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

What version of Spring Framework works best with which version of Spring Data JPA andSpring 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 theQuery by Example option you’ve been waiting for – the one where they finally handle domain objects that useJava’s Optional type in the getters. It’s been bugging you because anytime you had anOptional.EMPTY, it justblew 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 usesSpring Integration and Spring MVC. If you bump up the version, will those other dependencies run intoany 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 withthis 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 alreadybe selected.

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

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

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

Important

It doesn’t matter if you’re usingMaven orGradle. Either build system can consume Spring Boot dependencies and apply their collection ofmanaged 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 ofChapter 2,Creating a Web Application withSpring Boot.

That last part is key, so I’ll repeat it: whenCommon Vulnerabilities and Exposures (CVE) security vulnerabilities are reported to the Spring team, no matterwhich component of the Spring portfolio is impacted, the Spring Boot team will make a security-basedpatch 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 everythingwill follow.

To paraphrase Phil Webb, project lead for Spring Boot, if Spring Framework were a collection ofingredients, then Spring Boot would be apre-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 aone-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 alittle JavaScript.

Left arrow icon

Page1 of 7

Right arrow icon
Download code iconDownload 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 :9781803249896
Vendor :
VMware
Languages :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

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

Packt Subscriptions

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

Frequently bought together


Solutions Architect's Handbook
Solutions Architect's Handbook
Read more
Jan 2022590 pages
Full star icon4.4 (96)
eBook
eBook
€47.99€53.99
€67.99
€48.99
Spring Boot and Angular
Spring Boot and Angular
Read more
Dec 2022438 pages
Full star icon3.9 (17)
eBook
eBook
€26.98€29.99
€37.99
Learning Spring Boot 3.0
Learning Spring Boot 3.0
Read more
Dec 2022270 pages
Full star icon3.4 (14)
eBook
eBook
€23.99€26.99
€33.99
Stars icon
Total139.97
Solutions Architect's Handbook
€67.99
Spring Boot and Angular
€37.99
Learning Spring Boot 3.0
€33.99
Total139.97Stars icon

Table of Contents

16 Chapters
Part 1: The Basics of Spring BootChevron down iconChevron up icon
Part 1: The Basics of Spring Boot
Chapter 1: Core Features of Spring BootChevron down iconChevron up icon
Chapter 1: Core Features of Spring Boot
Technical requirements
Autoconfiguring Spring beans
Adding portfolio components using Spring Boot starters
Customizing the setup with configuration properties
Managing application dependencies
Summary
Part 2: Creating an Application with Spring BootChevron down iconChevron up icon
Part 2: Creating an Application with Spring Boot
Chapter 2: Creating a Web Application with Spring BootChevron down iconChevron up icon
Chapter 2: Creating a Web Application with Spring Boot
Using start.spring.io to build apps
Creating a Spring MVC web controller
Using start.spring.io to augment an existing project
Leveraging templates to create content
Creating JSON-based APIs
Hooking in Node.js to a Spring Boot web app
Summary
Chapter 3: Querying for Data with Spring BootChevron down iconChevron up icon
Chapter 3: Querying for Data with Spring Boot
Adding Spring Data to an existing Spring Boot application
DTOs, entities, and POJOs, oh my!
Creating a Spring Data repository
Using custom finders
Using Query By Example to find tricky answers
Using custom JPA
Summary
Chapter 4: Securing an Application with Spring BootChevron down iconChevron up icon
Chapter 4: Securing an Application with Spring Boot
Adding Spring Security to our project
Creating our own users with a custom security policy
Swapping hardcoded users with a Spring Data-backed set of users
Securing web routes and HTTP verbs
Securing Spring Data methods
Leveraging Google to authenticate users
Summary
Chapter 5: Testing with Spring BootChevron down iconChevron up icon
Chapter 5: Testing with Spring Boot
Adding JUnit 5 to the application
Creating tests for your domain objects
Testing web controllers with MockMVC
Testing data repositories with mocks
Testing data repositories with embedded databases
Adding Testcontainers to the application
Testing data repositories with Testcontainers
Testing security policies with Spring Security Test
Summary
Part 3: Releasing an Application with Spring BootChevron down iconChevron up icon
Part 3: Releasing an Application with Spring Boot
Chapter 6: Configuring an Application with Spring BootChevron down iconChevron up icon
Chapter 6: Configuring an Application with Spring Boot
Creating custom properties
Creating profile-based property files
Switching to YAML
Setting properties with environment variables
Ordering property overrides
Summary
Chapter 7: Releasing an Application with Spring BootChevron down iconChevron up icon
Chapter 7: Releasing an Application with Spring Boot
Creating an uber JAR
Baking a Docker container
Releasing your application to Docker Hub
Tweaking things in production
Summary
Chapter 8: Going Native with Spring BootChevron down iconChevron up icon
Chapter 8: Going Native with Spring Boot
What is GraalVM and why do we care?
Retrofitting our application for GraalVM
Running our native Spring Boot application inside GraalVM
Baking a Docker container with GraalVM
Summary
Part 4: Scaling an Application with Spring BootChevron down iconChevron up icon
Part 4: Scaling an Application with Spring Boot
Chapter 9: Writing Reactive Web ControllersChevron down iconChevron up icon
Chapter 9: Writing Reactive Web Controllers
What is reactive and why do we care?
Creating a reactive Spring Boot application
Serving data with a reactive GET method
Consuming incoming data with a reactive POST method
Serving a reactive template
Creating hypermedia reactively
Summary
Chapter 10: Working with Data ReactivelyChevron down iconChevron up icon
Chapter 10: Working with Data Reactively
Learning what it means to fetch data reactively
Picking a reactive data store
Creating a reactive data repository
Trying out R2DBC
Summary
IndexChevron down iconChevron up icon
Index
Why subscribe?
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book

Recommendations for you

Left arrow icon
Full-Stack Flask and React
Full-Stack Flask and React
Read more
Oct 2023408 pages
Full star icon3.8 (5)
eBook
eBook
€20.99€23.99
€29.99
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals
Read more
Nov 2024828 pages
Full star icon4.4 (5)
eBook
eBook
€26.98€29.99
€37.99
Real-World Web Development with .NET 9
Real-World Web Development with .NET 9
Read more
Dec 2024578 pages
Full star icon3.5 (4)
eBook
eBook
€26.98€29.99
€37.99
Django 5 By Example
Django 5 By Example
Read more
Apr 2024820 pages
Full star icon4.6 (40)
eBook
eBook
€26.98€29.99
€37.99
React and React Native
React and React Native
Read more
Apr 2024518 pages
Full star icon4.3 (10)
eBook
eBook
€23.99€26.99
€32.99
Scalable Application Development with NestJS
Scalable Application Development with NestJS
Read more
Jan 2025612 pages
Full star icon4.5 (6)
eBook
eBook
€20.99€23.99
€29.99
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
Read more
Nov 2023828 pages
Full star icon4.4 (74)
eBook
eBook
€31.99€35.99
€44.99
Responsive Web Design with HTML5 and CSS
Responsive Web Design with HTML5 and CSS
Read more
Sep 2022504 pages
Full star icon4.5 (57)
eBook
eBook
€23.99€26.99
€33.99
Modern Full-Stack React Projects
Modern Full-Stack React Projects
Read more
Jun 2024506 pages
Full star icon4.8 (9)
eBook
eBook
€23.99€26.99
€33.99
Learning Angular
Learning Angular
Read more
Jan 2025494 pages
Full star icon4 (6)
eBook
eBook
€23.99€26.99
€33.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconHalf star iconEmpty star icon3.4
(14 Ratings)
5 star57.1%
4 star0%
3 star0%
2 star7.1%
1 star35.7%
Filter icon Filter
Top Reviews

Filter reviews by




Pervaiz DostiyarJan 12, 2023
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
Nhat Quang TramFeb 15, 2023
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
Venkatesh VemanaMar 26, 2023
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
Gabriel J.Mar 10, 2023
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
AlazarMar 03, 2023
Full star iconFull star iconFull star iconFull star iconFull star icon5
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 reviewAmazon
  • Arrow left icon Previous
  • 1
  • 2
  • 3
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals
C# 11 and .NET 7 – Modern Cross-Platform Development Fundamentals
Read more
Nov 2022818 pages
Full star icon4.1 (54)
eBook
eBook
€26.98€29.99
€37.99
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
Read more
Nov 2023828 pages
Full star icon4.4 (74)
eBook
eBook
€31.99€35.99
€44.99
Responsive Web Design with HTML5 and CSS
Responsive Web Design with HTML5 and CSS
Read more
Sep 2022504 pages
Full star icon4.5 (57)
eBook
eBook
€23.99€26.99
€33.99
React and React Native
React and React Native
Read more
May 2022606 pages
Full star icon4.6 (17)
eBook
eBook
€26.98€29.99
€37.99
Building Python Microservices with FastAPI
Building Python Microservices with FastAPI
Read more
Aug 2022420 pages
Full star icon3.9 (9)
eBook
eBook
€25.99€28.99
€35.99
Right arrow icon

About the author

Profile icon Greg L. Turnquist
Greg L. Turnquist
LinkedIn icon
Greg L. Turnquist works on the Spring team at VMware. He is a committer to Spring Data, Spring Boot, R2DBC, Spring HATEOAS, and other Spring projects. He has written the Hacking with Spring Boot series as well as Packt's best-selling title, Learning Spring Boot 2.0 2nd Edition. He co-founded the Nashville Java User Group in 2010 and hasn't met a Java app (yet) that he doesn't like.He completed his master's degree in computer engineering at Auburn University and lives in the United States with his family.Be sure to check out his YouTube channel, Spring Boot Learning, where you learn about Spring Boot and have fun doing it at springbootlearning.
Read more
See other products by Greg L. Turnquist
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp