GitHub - Spring-Guides - Gs-Spring-Boot - Building An Application With Spring Boot - Learn How To Build An Application With Minimal Configuration - 5
GitHub - Spring-Guides - Gs-Spring-Boot - Building An Application With Spring Boot - Learn How To Build An Application With Minimal Configuration - 5
GitHub - Spring-Guides - Gs-Spring-Boot - Building An Application With Spring Boot - Learn How To Build An Application With Minimal Configuration - 5
Building an Application with Spring Boot :: Learn how to build an application with minimal
configuration.
spring.io/guides/gs/spring-boot/
Apache-2.0 License
663
stars
2.7k
forks
Star
Notifications
main
Go to file
View code
Table of Contents
What You Will build
What You Need
Learn What You Can Do with Spring Boot
Starting with Spring Initializr
Create a Simple Web Application
Create an Application class
Run the Application
Add Unit Tests
Add Production-grade Services
View Spring Boot’s Starters
JAR Support and Groovy Support
Summary
See Also
https://github.com/spring-guides/gs-spring-boot 1/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
This guide provides a sampling of how Spring Boot helps you accelerate
application
development. As you read more Spring Getting Started guides, you will see more
use cases
for Spring Boot. This guide is meant to give you a quick taste of Spring Boot.
If you want to
create your own Spring Boot-based project, visit
Spring Initializr, fill in your project details,
pick your
options, and download a bundled up project as a zip file.
https://raw.githubusercontent.com/spring-guides/getting-started-
macros/main/how_to_complete_this_guide.adoc
Spring Boot offers a fast way to build applications. It looks at your classpath and at the
beans you have configured, makes reasonable assumptions about what you are missing,
and
adds those items. With Spring Boot, you can focus more on business features and less
on
infrastructure.
The following examples show what Spring Boot can do for you:
Is Spring MVC on the classpath? There are several specific beans you almost always
need,
and Spring Boot adds them automatically. A Spring MVC application also needs a
servlet
container, so Spring Boot automatically configures embedded Tomcat.
Is Jetty on the classpath? If so, you probably do NOT want Tomcat but instead want
embedded Jetty. Spring Boot handles that for you.
Is Thymeleaf on the classpath? If so, there are a few beans that must always be added
to
your application context. Spring Boot adds them for you.
These are just a few examples of the automatic configuration Spring Boot provides. At the
same time, Spring Boot does not get in your way. For example, if Thymeleaf is on your
path,
Spring Boot automatically adds a SpringTemplateEngine to your application context.
But if
you define your own SpringTemplateEngine with your own settings, Spring Boot does
not
add one. This leaves you in control with little effort on your part.
Note Spring Boot does not generate code or make edits to your files. Instead, when
https://github.com/spring-guides/gs-spring-boot 2/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
you
start your application, Spring Boot dynamically wires up beans and settings
and applies
them to your application context.
1. Navigate to https://start.spring.io.
This service pulls in all the dependencies you need
for an application and does most of the setup for you.
2. Choose either Gradle or Maven and the language you want to use. This guide assumes
that you chose Java.
4. Click Generate.
5. Download the resulting ZIP file, which is an archive of a web application that is
configured with your choices.
If your IDE has the Spring Initializr integration, you can complete this process
Note
from your IDE.
You can also fork the project from Github and open it in your IDE or other
Note
editor.
link:initial/src/main/java/com/example/springboot/HelloController.java[]
The class is flagged as a @RestController , meaning it is ready for use by Spring MVC to
handle web requests. @GetMapping maps / to the index() method. When invoked from
a
browser or by using curl on the command line, the method returns pure text. That is
because @RestController combines @Controller and @ResponseBody , two annotations
that
results in web requests returning data rather than a view.
The Spring Initializr creates a simple application class for you. However, in this case,
it is too
simple. You need to modify the application class to match the following listing
(from
src/main/java/com/example/springboot/Application.java ):
link:complete/src/main/java/com/example/springboot/Application.java[]
https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/spring-
boot-application-new-path.adoc
There is also a CommandLineRunner method marked as a @Bean , and this runs on start up.
It
retrieves all the beans that were created by your application or that were
automatically
added by Spring Boot. It sorts them and prints them out.
./gradlew bootRun
If you use Maven, run the following command in a terminal window (in the complete )
directory:
./mvnw spring-boot:run
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$
https://github.com/spring-guides/gs-spring-boot 4/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfig
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwarePro
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping
Now run the service with curl (in a separate terminal window), by running the following
command (shown with its output):
$ curl localhost:8080
If you use Gradle, add the following dependency to your build.gradle file:
link:complete/build.gradle[]
link:complete/pom.xml[]
https://github.com/spring-guides/gs-spring-boot 5/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
Now write a simple unit test that mocks the servlet request and response through your
endpoint, as the following listing (from
src/test/java/com/example/springboot/HelloControllerTest.java ) shows:
link:complete/src/test/java/com/example/springboot/HelloControllerTest.java[]
MockMvc comes from Spring Test and lets you, through a set of convenient builder
classes,
send HTTP requests into the DispatcherServlet and make assertions about the
result. Note
the use of @AutoConfigureMockMvc and @SpringBootTest to inject a
MockMvc instance.
Having used @SpringBootTest , we are asking for the whole application
context to be
created. An alternative would be to ask Spring Boot to create only the web
layers of the
context by using @WebMvcTest . In either case, Spring Boot automatically
tries to locate the
main application class of your application, but you can override it or
narrow it down if you
want to build something different.
As well as mocking the HTTP request cycle, you can also use Spring Boot to write a simple
full-stack integration test. For example, instead of (or as well as) the mock test shown
earlier,
we could create the following test (from
src/test/java/com/example/springboot/HelloControllerIT.java ):
link:complete/src/test/java/com/example/springboot/HelloControllerIT.java[]
If you are building a web site for your business, you probably need to add some
management
services. Spring Boot provides several such services (such as health, audits,
beans, and
more) with its
actuator module.
If you use Gradle, add the following dependency to your build.gradle file:
link:complete/build.gradle[]
If you use Maven, add the following dependency to your pom.xml file:
link:complete/pom.xml[]
Then restart the application. If you use Gradle, run the following command in a terminal
window (in the complete directory):
https://github.com/spring-guides/gs-spring-boot 6/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
./gradlew bootRun
If you use Maven, run the following command in a terminal window (in the complete
directory):
./mvnw spring-boot:run
You should see that a new set of RESTful end points have been added to the application.
These are management services provided by Spring Boot. The following listing shows typical
output:
management.endpoint.configprops-
org.springframework.boot.actuate.autoconfigure.context.properties.ConfigurationProper
management.endpoint.env-
org.springframework.boot.actuate.autoconfigure.env.EnvironmentEndpointProperties
management.endpoint.health-
org.springframework.boot.actuate.autoconfigure.health.HealthEndpointProperties
management.endpoint.logfile-
org.springframework.boot.actuate.autoconfigure.logging.LogFileWebEndpointProperties
management.endpoints.jmx-
org.springframework.boot.actuate.autoconfigure.endpoint.jmx.JmxEndpointProperties
management.endpoints.web-
org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties
management.endpoints.web.cors-
org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties
management.health.diskspace-
org.springframework.boot.actuate.autoconfigure.system.DiskSpaceHealthIndicatorPropert
management.info-
org.springframework.boot.actuate.autoconfigure.info.InfoContributorProperties
management.metrics-
org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties
management.metrics.export.simple-
org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleProperties
management.server-
org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties
actuator/health
actuator
https://github.com/spring-guides/gs-spring-boot 7/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
You can check the health of the application by running the following command:
$ curl localhost:8080/actuator/health
{"status":"UP"}
You can try also to invoke shutdown through curl, to see what happens when you have not
added the necessary line (shown in the preceding note) to application.properties :
{"timestamp":1401820343710,"error":"Not Found","status":404,"message":"","path":"/act
Because we did not enable it, the requested endpoint is not available (because the endpoint
does not
exist).
For more details about each of these REST endpoints and how you can tune their settings
with an application.properties file (in src/main/resources ), see the
the documentation
about the endpoints.
However, Spring Boot does more than that. It supports not only traditional WAR file
deployments but also lets you put together executable JARs, thanks to Spring Boot’s loader
module. The various guides demonstrate this dual support through the
spring-boot-
gradle-plugin and spring-boot-maven-plugin .
On top of that, Spring Boot also has Groovy support, letting you build Spring MVC web
applications with as little as a single file.
https://github.com/spring-guides/gs-spring-boot 8/10
11/29/21, 8:37 AM GitHub - spring-guides/gs-spring-boot: Building an Application with Spring Boot :: Learn how to build an application with mini…
Create a new file called app.groovy and put the following code in it:
@RestController
class ThisWillActuallyRun {
@GetMapping("/")
String home() {
It does not matter where the file is. You can even fit an application that small
Note
inside a single tweet!
From a different terminal window, run the following curl command (shown with its output):
$ curl localhost:8080
Hello, World!
Spring Boot does this by dynamically adding key annotations to your code and using
Groovy Grape to pull down the libraries that are needed
to make the app run.
Summary
Congratulations! You built a simple web application with Spring Boot and learned how it
can
ramp up your development pace. You also turned on some handy production services.
This
is only a small sampling of what Spring Boot can do. See
Spring Boot’s online docs
for much
more information.
See Also
The following guides may also be helpful:
https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/footer.adoc
Releases
21
tags
Packages
No packages published
Contributors 26
+ 15 contributors
Languages
Java 91.0%
Shell 9.0%
https://github.com/spring-guides/gs-spring-boot 10/10