What is Spring Boot?
What is Spring Boot?
What We’ll Be Learning
In aprevious article, we learned how components of a Spring application are configured as Spring beans and injected as dependencies into other components by the Inversion of Control (IoC) container. For example, one component of web applications is the controller, and we can mark a class as a controller using the@RestControllerannotation.
import org.springframework.web.bind.annotation.*;
@RequestMapping("/restaurants")@RestControllerpublic class RestaurantController {}
Copy to clipboard
import org.springframework.web.bind.annotation.*;
@RequestMapping("/restaurants")@RestControllerpublic class RestaurantController {}
When our app is run, this controller class will be registered as a bean and used to define routes available in our API.
If you run the application and look closely at the terminal output, you’ll notice that our app is doing a lot more than running the controller code we defined. For example:
- ASpring Data JPArepository is bootstrapped
- ATomcatserver is initialized
- AWebApplicationContextis initialized
- AnH2Dialectis used
- We see an option toExplicitly configure spring.jpa.open-in-view
- The Tomcat server is started onport(s): 4000
$ ./mvnw spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.0)
........ Starting CoffeeOrdersApplication using Java 11.0.10...
........ No active profile set, falling back to default profiles: default
........ Bootstrapping Spring Data JPA repositories in DEFAULT mode.
........ Finished Spring Data repository scanning in 42 ms. Found 1 JPA repository interfaces.
........ Tomcat initialized with port(s): 4000 (http)
........ Starting service [Tomcat]
........ Starting Servlet engine: [Apache Tomcat/9.0.46]
........ Initializing Spring embedded WebApplicationContext
........ Root WebApplicationContext: initialization completed in 1369 ms
........ HHH000204: Processing PersistenceUnitInfo [name: default]
........ HHH000412: Hibernate ORM core version 5.4.31.Final
........ HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
........ HikariPool-1 - Starting...
........ HikariPool-1 - Start completed.
........ HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
........ HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
........ Initialized JPA EntityManagerFactory for persistence unit 'default'
........ spring.jpa.open-in-view is enabled by default.
........ Therefore, database queries may be performed during view rendering.
........ Explicitly configure spring.jpa.open-in-view to disable this warning
........ Tomcat started on port(s): 4000 (http) with context path ''
........ Started SpringCapstoneApplication in 9.187 seconds (JVM running for 9.726)
........ Application availability state LivenessState changed to CORRECT
........ Application availability state ReadinessState changed to ACCEPTING_TRAFFIC
This raises a few questions: How was that controller converted into a bean? Where are Spring Data JPA, H2Dialect, and Tomcat coming from? Who told them to start up like that? Where do I “configure” things?
The reason is Spring Boot! Spring Boot is a collection of tools that extends the Spring framework and makes it easier to build applications quickly. There are too many Spring Boot tools to cover in one article, so we will focus on these four, which will answer our questions above:
- “Starters”
- Auto-configuration
- Custom configurations withapplication.properties
- Distribution of your application
By covering these four features, you’ll begin to see how Spring Boot is added to our Spring projects and how it makes building apps easier.
Downloads
Every Spring project generated by start.spring.io includes Spring Boot, so the code included in this article will look similar to most applications you write.
To keep things specific, however, we’ve provided an example application so that you can follow along throughout the article.
Download the example Spring Boot application hereand double-click on the .zip file to uncompress it.
Starters
If you look at thepom.xmlof our Spring Boot application, you’ll see thespring-boot-start-jpaandspring-boot-starter-webdependencies.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
Copy to clipboard
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
These are calledSpring Boot “starters”. Each one represents a set of dependencies with which to run our application. For example, thespring-boot-starter-webdependency instructs Spring Boot to configure Tomcat for running a server and SpringMVC(Model-View-Controller) for routingHTTP requests.spring-boot-starter-data-jpasets up JPA and Hibernate for database access.
There are other starters likespring-boot-starter-testwhich includes common testing libraries such as JUnit Jupiter, Hamcrest, and Mockito, andspring-boot-starter-parent, which provides thespring-boot:runcommand.
Auto-Configuration
We understand where dependencies like Tomcat are defined, but how are they hooked into our application?
If we look at the two imports at the top ofCoffeeOrdersApplication.java(located insrc\main\java\com\codecademy\coffeeorders), we’ll see theSpringApplicationclass and@SpringBootApplicationannotation from theorg.springframework.bootpackage:
package com.codecademy.coffeeorders;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class CoffeeOrdersApplication {
public static void main(String[] args) { SpringApplication.run(CoffeeOrdersApplication.class, args); }
}
Copy to clipboard
package com.codecademy.coffeeorders;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class CoffeeOrdersApplication {
public static void main(String[] args) { SpringApplication.run(CoffeeOrdersApplication.class, args); }
}
SpringApplication
Remember when we said that the Spring IoC container configures beans for us? TheSpringApplicationclass is responsible for starting up that container. We can see that in the line:
........ Initializing Spring embedded WebApplicationContext
In Java, the IoC container is represented by anapplication context. This is the thing that receives beans and enables Spring to inject them into other components. In Java, the application context appears as aApplicationContextinterface. In our specific case, this app is using the classWebApplicationContext, a web-specific implementation ofApplicationContext.
@SpringBootApplication
The@SpringBootApplicationannotation is equivalent to@Configuration,@ComponentScan, and@EnableAutoConfiguration. The first two are from the Spring framework, but the third,@EnableAutoConfiguration, is from Spring Boot.
This annotation enables Spring Boot to review our dependencies (such asspring-boot-starter-data-jpaandh2) and assume the intended purpose of the application. It will configure and run the application to best fit the assumed purpose.
This explains theSpring Data JPA,Tomcat, andH2Dialectlines in our original code snippet: Spring Boot knows to bootstrap JPA repositories, start aTomcatserver, and use an H2 dialect becausespring-boot-starter-data-jpa,spring-boot-starter-web, andh2are listed as dependencies in thepom.xml.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency>
Copy to clipboard
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency>
Here’s another way to explain it, from the Spring documentation:
@EnableAutoConfiguration…tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
Webb, Phillip et al. “Spring Boot Reference Documentation“. Accessed June 29, 2021.
Custom Configuration with application.properties
In our original terminal output, we saw the lines:
........ Explicitly configure spring.jpa.open-in-view to disable this warning
........ Tomcat started on port(s): 4000 (http) with context path ''
When we start our application with./mvnw spring-boot:run, Spring Boot does some tasks by default: it makes some assumptions, like using port 8080, but it also checks for additional configuration instructions in theapplication.propertiesfile. This allows us to make high-level changes to our application without writing any Java code.
For example, you can override the default 8080 port using:
server.port=4000
You can disable JPA warnings:
spring.jpa.open-in-view=false
Or customize the level of logging in your application:
logging.level.org.springframework=DEBUG
In the case of the downloadable application we provided, theapplication.propertiesfile customizes the database behavior, such as the local file to use for storage:
spring.datasource.url=jdbc:h2:file:~/coffeeorders
A longer list of application properties are available in the Spring docs.
Distribution
So far we’ve solved the mysteries of that Spring Boot terminal output, which appeared on your own computer. But what about the output that appears on Codecademy when you run a Spring Boot app?
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.codecademy:ccapplication >--------------------
[INFO] Building codecademy-learning-environment-app 0.0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ ccapplication ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ ccapplication ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /home/ccuser/workspace/spring-capstone/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.162 s
[INFO] Finished at: 2021-06-30T00:45:54Z
[INFO] ------------------------------------------------------------------------
Java applications are often packaged into an executable file called ajar, which you can see in the above code. Spring Boot provides an easy way to bundle your code and dependencies into a jar via thespring-boot-maven-plugindependency. This is included by default when we download a project fromstart.spring.io.
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>
Copy to clipboard
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>
When we run applications on our Codecademy platform–or when you deploy your next app to the cloud–you are using Spring Boot to bundle your code and dependencies into a jar.
Note that there are other Spring Boot deployment tools such asSpring Boot Actuator, but they are not necessary to understand this article.
Practice
You’ve made it to the end! We’ve provided some assessments here for you to check your understanding. If you don’t feel confident in answering these questions, that’s okay! Spend some more time with the article above and try again later.
Conclusion
Congrats! This article gave you a sense of how Spring Boot makes it easier to work with the Spring framework. There are many more aspects of Spring Boot we didn’t cover, but at this point you should be able to:
- Describe the significance of dependencies likespring-boot-starter-webin yourpom.xml
- Explain whatSpringApplicationdoes
- Explain what@SpringBootApplication, and more specifically the underlying@EnableAutoConfigurationannotation, enables your application to do
- Identify whenapplication.propertiesis used
- Explain theBUILD SUCCESSoutput occasionally shown in the Codecademy environment
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Complete Payment to Unlock Full Guide & Source Code
You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.
Ready to access the complete step-by-step tutorial?
Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.
What is SQLite?
Next BlueprintWhat is Streamlit? A Complete Guide for Building Data Apps
Related Blueprints & Guides
View all 166 →Accessibility on the Platform
Codecademy is committed to providing a high-quality learning experience for all learners. That includes accommodating different usage forms such as auditory, motor, or visual restrictions, limited hardware, or other acce...
Web developmentAffordances, Signifiers, and Clickability
For users on the web, the mouse click is perhaps the most fundamental human-computer interaction. The webbecamethe web partially through the power ofhypertext, or text in one document that links to other documents or res...
Web developmentAuthentication and OAuth
Authenticationis the process used by applications to determine and confirm identities of users. It ensures that the correct content is shown to users. More importantly, it ensures that incorrect content is secured and u...
Ready to build production-grade AI systems?
Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.