We will start with building our first Spring Boot application in this lesson. We will use Maven to manage dependencies.
The following steps are involved in starting up with a Spring Boot application:
- Configure
spring-boot-starter-parent
in your pom.xml
file. - Configure the
pom.xml
file with the required starter projects. - Configure
spring-boot-maven-plugin
to be able to run the application. - Create your first Spring Boot launch class.
Let's start with step 1, configuring the starter projects.
Configure spring-boot-starter-parent
Let's start with a simple pom.xml
file with spring-boot-starter-parent
:
The first question is this: why do we need spring-boot-starter-parent
?
A spring-boot-starter-parent
dependency contains the default versions of Java to use, the default versions of dependencies that Spring Boot uses, and the default configuration of the Maven plugins.
Note
The spring-boot-starter-parent
dependency is the parent POM providing dependency and plugin management for Spring Boot-based applications.
Let's look at some of the code inside spring-boot-starter-parent
to get a deeper understanding about spring-boot-starter-parent
.
spring-boot-starter-parent
The spring-boot-starter-parent
dependency inherits from spring-boot-dependencies
, which is defined at the top of the POM. The following code snippet shows an extract from spring-boot-starter-parent
:
The spring-boot-dependencies
provides default dependency management for all the dependencies that Spring Boot uses. The following code shows the different versions of various dependencies that are configured in spring-boot-dependencies
:
If we want to override a specific version of a dependency, we can do that by providing a property with the right name in the pom.xml
file of our application. The following code snippet shows an example of configuring our application to use version 1.10.20 of Mockito:
The following are some of the other things defined in spring-boot-starter-parent
:
- The default Java version
<java.version>1.8</java.version>
- The default configuration for Maven plugins:
maven-failsafe-plugin
maven-surefire-plugin
git-commit-id-plugin
Compatibility between different versions of frameworks is one of the major problems faced by developers. How do I find the latest Spring Session version that is compatible with a specific version of Spring? The usual answer would be to read the documentation. However, if we use Spring Boot, this is made simple by spring-boot-starter-parent
. If we want to upgrade to a newer Spring version, all that we need to do is to find the spring-boot-starter-parent
dependency for that Spring version. Once we upgrade our application to use that specific version of spring-boot-starter-parent
, we would have all the other dependencies upgraded to the versions compatible with the new Spring version. One less problem for developers to handle. Always make me happy.
Configure pom.xml with the Required Starter Projects
Whenever we want to build an application in Spring Boot, we would need to start looking for starter projects. Let's focus on understanding what a starter project is.
Understanding Starter Projects
Starters are simplified dependency descriptors customized for different purposes. For example, spring-boot-starter-web
is the starter for building web application, including RESTful, using Spring MVC. It uses Tomcat as the default embedded container. If I want to develop a web application using Spring MVC, all we would need to do is include spring-boot-starter-web
in our dependencies, and we get the following automatically pre-configured:
- Spring MVC
- Compatible versions of
jackson-databind
(for binding) and hibernate-validator (for form validation) spring-boot-starter-tomcat
(starter project for Tomcat)
The following code snippet shows some of the dependencies configured in spring-boot-starter-web
:
As we can see in the preceding snippet, when we usespring-boot-starter-web
, we get a lot of frameworks auto-configured.
For the web application we would like to build, we would also want to do some good unit testing and deploy it on Tomcat. The following snippet shows the different starter dependencies that we would need. We would need to add this to our pom.xml
file:
We add three starter projects:
- We've already discussed
spring-boot-starter-web
. It provides us with the frameworks needed to build a web application with Spring MVC. - The
spring-boot-starter-test
dependency provides the following test frameworks needed for unit testing:- JUnit: Basic unit test framework
- Mockito: For mocking
- Hamcrest, AssertJ: For readable asserts
- Spring Test: A unit testing framework for spring-context based applications
- The
spring-boot-starter-tomcat
dependency is the default for running web applications. We include it for clarity. The spring-boot-starter-tomcat
is the starter for using Tomcat as the embedded servlet container.
We now have our pom.xml
file configured with the starter parent and the required starter projects. Let's add spring-boot-maven-plugin
now, which would enable us to run Spring Boot applications.
Configuring spring-boot-maven-plugin
When we build applications using Spring Boot, there are a couple of situations that are possible:
- We would want to run the applications in place without building a JAR or a WAR
- We would want to build a JAR and a WAR for later deployment
The spring-boot-maven-plugin
dependency provides capabilities for both of the preceding situations. The following snippet shows how we can configure spring-boot-maven-plugin
in an application:
The spring-boot-maven-plugin
dependency provides several goals for a Spring Boot application. The most popular goal is run (this can be executed as mvn spring-boot:run
on the command prompt from the root folder of the project).
Creating Your First Spring Boot Launch Class
The following class explains how to create a simple Spring Boot launch class. It uses the static run method from the SpringApplication
class, as shown in the following code snippet:
The preceding code is a simple Java main
method executing the static run
method on the SpringApplication
class.
The SpringApplication Class
The SpringApplication
class can be used to Bootstrap and launch a Spring application from a Java main
method.
The following are the steps that are typically performed when a Spring Boot application is bootstrapped:
- Create an instance of Spring's
ApplicationContext
. - Enable the functionality to accept command-line arguments and expose them as Spring properties.
- Load all the Spring beans as per the configuration.
The @SpringBootApplication Annotation
The @SpringBootApplication
annotation is a shortcut for three annotations:
@Configuration
: Indicates that this a Spring application context configuration file.@EnableAutoConfiguration
: Enables auto-configuration, an important feature of Spring Boot. We will discuss auto-configuration later in a separate section.@ComponentScan
: Enables scanning for Spring beans in the package of this class and all its sub packages.
Running Our Hello World Application
We can run the Hello World application in multiple ways. Let's start running it with the simplest option--running as a Java application. In your IDE, right-click on the application class and run it as Java Application. The following screenshot shows some of the log from running our Hello World
application:
The following are the key things to note:
- Tomcat server is launched on port
8080
--Tomcat started on port(s): 8080 (http)
. DispatcherServlet
is configured. This means that Spring MVC Framework is ready to accept requests--Mapping servlet: 'dispatcherServlet' to [/]
.- Four filters--
characterEncodingFilter
, hiddenHttpMethodFilter
, httpPutFormContentFilter
and requestContextFilter
--are enabled by default - The default error page is configured--
Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
- WebJars are autoconfigured. WebJars enable dependency management for static dependencies such as Bootstrap and query--
Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
The following screenshot shows the application layout as of now. We have just two files, pom.xml
and Application.java
:
With a simple pom.xml
file and one Java class, we were able to get to launch the Spring MVC application, with all the preceding functionality described. The most important thing about Spring Boot is to understand what happens in the background. Understanding the preceding start up log is the first. Let's look at the Maven dependencies to get a deeper picture.
The following screenshot shows some of the dependencies that are configured with the basic configuration in the pom.xml
file that we created:
Spring Boot does a lot of magic. Once you have the application configured and running, I recommend that you play around with it to gain a deeper understanding that will be useful when you are debugging problems.
As Spiderman says, with great power, comes great responsibility. This is absolutely true in the case of Spring Boot. In the time to come, the best developers with Spring Boot would be the ones who understand what happens in the background--dependencies and auto-configuration.
To enable us to understand auto-configuration further, let's expand our application class to include a few more lines of code:
We get all the beans that are defined in the Spring application context and print their names. When Application.java
is run as a Java program, it prints the list of beans, as shown in the following output:
Important things to think about are as follows:
- Where are these beans defined?
- How are these beans created?
That's the magic of Spring auto-configuration.
Whenever we add a new dependency to a Spring Boot project, Spring Boot auto-configuration automatically tries to configure the beans based on the dependency.
For example, when we add a dependency in spring-boot-starter-web
, the following beans are auto-configured:
basicErrorController
, handlerExceptionResolver
: It is the basic exception handling. It shows a default error page when an exception occurs.beanNameHandlerMapping
: It is used to resolve paths to a handler (controller).characterEncodingFilter
: It provides default character encoding UTF-8.dispatcherServlet
: It is the front controller in Spring MVC applications.jacksonObjectMapper
: It translates objects to JSON and JSON to objects in REST services.messageConverters
: It is the default message converters to convert from objects into XML or JSON and vice versa.multipartResolver
: It provides support to upload files in web applications.mvcValidator
: It supports validation of HTTP requests.viewResolver
: It resolves a logical view name to a physical view.propertySourcesPlaceholderConfigurer
: It supports the externalization of application configuration.requestContextFilter
: It defaults the filter for requests.restTemplateBuilder
: It is used to make calls to REST services.tomcatEmbeddedServletContainerFactory
: Tomcat is the default embedded servlet container for Spring Boot-based web applications.
In the next section, let's look at some of the starter projects and the auto-configuration they provide.
The following table shows some of the important starter projects provided by Spring Boot:
Until now, we have set up a basic web application and understood some of the important concepts related to Spring Boot:
- Auto-configuration
- Starter projects
spring-boot-maven-plugin
spring-boot-starter-parent
- Annotation
@SpringBootApplication
Now let's shift our focus to understanding what REST is and building a REST Service.