Building an Application with Spring Boot :: Learn how to build an application with minimal configuration. https://spring.io/guides/gs/spring-boot/
Greg Turnquist dea18a37f8 Add 'groovy' tag since part of this guide uses CLI 10 年之前
complete Remove version number from Spring Boot starters 10 年之前
initial Move final build file to the beginning and update guides to reflect this 10 年之前
test Convert to mvn compile for initial codeset 10 年之前
.gitignore Convert to asciidoctor 11 年之前
LICENSE.code.txt Add ASLv2 license for the code in this repo 11 年之前
LICENSE.writing.txt Apply http://creativecommons.org/licenses/by-nd/3.0/ to written work in this repo 11 年之前
README.adoc Add 'groovy' tag since part of this guide uses CLI 10 年之前

README.adoc

---
tags: [spring-boot, groovy]
projects: [spring-boot]
---
:spring_boot_version: 1.0.0.RC3
:spring-boot: https://github.com/spring-projects/spring-boot
:toc:
:icons: font
:source-highlighter: prettify
:project_id: gs-spring-boot
This guide provides a sampling of how {spring-boot}[Spring Boot] helps you accelerate and facilitate application development. As you read more Spring Getting Started guides, you will see more use cases for Spring Boot.
It is meant to give you a quick taste of Spring Boot. If you want to create your own Spring Boot-based project, visit
http://start.spring.io/[Spring Initializr], fill in your project details, pick your options, and you can download either
a Maven build file, or a bundled up project as a zip file.

== What you'll build
You'll build a simple web application with Spring Boot and add some useful services to it.

== What you'll need

include::https://raw.github.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[]

include::https://raw.github.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[]


[[scratch]]
== Set up the project

include::https://raw.github.com/spring-guides/getting-started-macros/master/build_system_intro.adoc[]

include::https://raw.github.com/spring-guides/getting-started-macros/master/create_directory_structure_hello.adoc[]


include::https://raw.github.com/spring-guides/getting-started-macros/master/create_both_builds.adoc[]

`build.gradle`
// AsciiDoc source formatting doesn't support groovy, so using java instead
[source,java]
----
include::initial/build.gradle[]
----

== Learn what you can do with Spring Boot

Spring Boot offers a fast way to build applications. It looks at your classpath and at beans you have configured, makes reasonable assumptions about what you're missing, and adds it. With Spring Boot you can focus more on business features and less on infrastructure.

For example:

- Got Spring MVC? There are several specific beans you almost always need, and Spring Boot adds them automatically. A Spring MVC app also needs a servlet container, so Spring Boot automatically configures embedded Tomcat.
- Got Jetty? If so, you probably do NOT want Tomcat, but instead embedded Jetty. Spring Boot handles that for you.
- Got Thymeleaf? 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 doesn't get in your way. For example, if Thymeleaf is on your path, Spring Boot adds a `SpringTemplateEngine` to your application context automatically. But if you define your own `SpringTemplateEngine` with your own settings, then Spring Boot won't add one. This leaves you in control with little effort on your part.

NOTE: Spring Boot doesn't generate code or make edits to your files. Instead, when you start up your application, Spring Boot dynamically wires up beans and settings and applies them to your application context.

== Create a simple web application
Now you can create a web controller for a simple web application.

`src/main/java/hello/HelloController.java`
[source,java]
----
include::initial/src/main/java/hello/HelloController.java[]
----

The class is flagged as a `@RestController`, meaning it's ready for use by Spring MVC to handle web requests. `@RequestMapping` maps `/` to the `index()` method. When invoked from a browser or using curl on the command line, the method returns pure text. That's because `@RestController` combines `@Controller` and `@ResponseBody`, two annotations that results in web requests returning data rather than a view.

== Create an Application class
Here you create an `Application` class with the components:

`src/main/java/hello/Application.java`
[source,java]
----
include::initial/src/main/java/hello/Application.java[]
----

- `@Configuration` tags the class as a source of bean definitions for the application context.
- `@EnableAutoConfiguration` tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
- Normally you would add `@EnableWebMvc` for a Spring MVC app, but Spring Boot adds it automatically when it sees **spring-webmvc** on the classpath. This flags the application as a web application and activates key behaviors such as setting up a `DispatcherServlet`.
- `@ComponentScan` tells Spring to look for other components, configurations, and services in the the `hello` package, allowing it to find the `HelloController`.

The `main()` method uses Spring Boot's `SpringApplication.run()` method to launch an application. Did you notice that there wasn't a single line of XML? No **web.xml** file either. This web application is 100% pure Java and you didn't have to deal with configuring any plumbing or infrastructure.

The `run()` method returns an `ApplicationContext` and this application then retrieves all the beans that were created either by your app or were automatically added thanks to Spring Boot. It sorts them and prints them out.

== Run the application
To run the application, execute:

[subs="attributes"]
----
./gradlew build && java -jar build/libs/{project_id}-0.1.0.jar
----

If you are using Maven, execute:

[subs="attributes"]
----
mvn package && java -jar target/{project_id}-0.1.0.jar
----

You should see some output like this:

....
Let's inspect the beans provided by Spring Boot:
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$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
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
....

You can clearly see **org.springframework.boot.autoconfigure** beans. There is also a `tomcatEmbeddedServletContainerFactory`.

Check out the service.

....
$ curl localhost:8080
Greetings from Spring Boot!
....

== Switch from Tomcat to Jetty
What if you prefer Jetty over Tomcat? Jetty and Tomcat are both compliant servlet containers, so it should be easy to switch. With Spring Boot, it is!

Change your `build.gradle` to exclude Tomcat then add Jetty to the list of dependencies:

[source,groovy]
----
include::complete/build.gradle[tag=jetty]
----

If you are using Maven, the changes look like this:

[source,xml]
----
include::complete/pom.xml[tag=jetty]
----

This change isn't about comparing Tomcat vs. Jetty. Instead, it demonstrates how Spring Boot reacts to what is on your classpath.

As you can see below, the code is the same as before:

`src/main/java/hello/Application.java`
[source,java]
----
include::complete/src/main/java/hello/Application.java[]
----


== Re-run the application

Run the app again:

[subs="attributes"]
----
./gradlew build && java -jar build/libs/{project_id}-0.1.0.jar
----

If you are using Maven, execute:

[subs="attributes"]
----
mvn package && java -jar target/{project_id}-0.1.0.jar
----

Now check out the output:

....
Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
faviconHandlerMapping
faviconRequestHandler
handlerExceptionResolver
helloController
hiddenHttpMethodFilter
httpRequestHandlerAdapter
jettyEmbeddedServletContainerFactory
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$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedJetty
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
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
viewControllerHandlerMapping
....

There is little change from the previous output, except there is no longer a `tomcatEmbeddedServletContainerFactory`. Instead, there is a new `jettyEmbeddedServletContainer`.

Otherwise, everything is the same, as it should be. Most beans listed above provide Spring MVC's production-grade features. Simply swapping one part, the servlet container, shouldn't cause a system-wide ripple.

== Add production-grade services
If you are building a web site for your business, you probably need to add some management services. Spring Boot provides several out of the box with its https://github.com/spring-projects/spring-boot/blob/master/spring-boot-actuator/README.md[actuator module], such as health, audits, beans, and more.

Add this to your build file's list of dependencies:

[source,groovy]
----
include::complete/build.gradle[tag=actuator]
----

If you are using Maven, add this to your list of dependencies:

[source,xml]
----
include::complete/pom.xml[tag=actuator]
----

Then restart the app:

[subs="attributes"]
----
./gradlew build && java -jar build/libs/{project_id}-0.1.0.jar
----

If you are using Maven, execute:

[subs="attributes"]
----
mvn package && java -jar target/{project_id}-0.1.0.jar
----

You will see a new set of RESTful end points added to the application. These are management services provided by Spring Boot.

....
2013-08-01 08:03:42.592 INFO 43851 ... Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.Map org.springframework.boot.ops.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2013-08-01 08:03:42.592 INFO 43851 ... Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.ops.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2013-08-01 08:03:42.844 INFO 43851 ... Mapped URL path [/env] onto handler of type [class org.springframework.boot.ops.endpoint.EnvironmentEndpoint]
2013-08-01 08:03:42.844 INFO 43851 ... Mapped URL path [/health] onto handler of type [class org.springframework.boot.ops.endpoint.HealthEndpoint]
2013-08-01 08:03:42.844 INFO 43851 ... Mapped URL path [/beans] onto handler of type [class org.springframework.boot.ops.endpoint.BeansEndpoint]
2013-08-01 08:03:42.844 INFO 43851 ... Mapped URL path [/info] onto handler of type [class org.springframework.boot.ops.endpoint.InfoEndpoint]
2013-08-01 08:03:42.845 INFO 43851 ... Mapped URL path [/metrics] onto handler of type [class org.springframework.boot.ops.endpoint.MetricsEndpoint]
2013-08-01 08:03:42.845 INFO 43851 ... Mapped URL path [/trace] onto handler of type [class org.springframework.boot.ops.endpoint.TraceEndpoint]
2013-08-01 08:03:42.845 INFO 43851 ... Mapped URL path [/dump] onto handler of type [class org.springframework.boot.ops.endpoint.DumpEndpoint]
2013-08-01 08:03:42.845 INFO 43851 ... Mapped URL path [/shutdown] onto handler of type [class org.springframework.boot.ops.endpoint.ShutdownEndpoint]
....

They include: errors, http://localhost:8080/env[environment], http://localhost:8080/health[health], http://localhost:8080/beans[beans], http://localhost:8080/info[info], http://localhost:8080/metrics[metrics], http://localhost:8080/trace[trace], http://localhost:8080/dump[dump], and shutdown.

It's easy to check the health of the app.

----
$ curl localhost:8080/health
ok
----

You can invoke shutdown through curl.

----
$ curl -X POST localhost:8080/shutdown
----

The response shows that shutdown through REST is currently disabled by default:
----
{"message":"Shutdown not enabled, sorry."}
----

Whew! You probably don't want that until you are ready to turn on proper security settings, if at all.

For more details about each of these REST points and how you can tune their settings with an `application.properties` file, check out the {spring-boot}[Spring Boot] project.

== View Spring Boot's starters
You have seen some of Spring Boot's **starters**. You can see them all https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters[here].

== JAR support and Groovy support
The last example showed how Spring Boot makes it easy to wire beans you may not be aware that you need. And it showed how to turn on convenient management services.

But Spring Boot does yet more. It supports not only traditional WAR file deployments, but also makes it easy to 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, allowing you to build Spring MVC web apps with as little as a single file.

Create a new file called **app.groovy** and put the following code in it:

[source,groovy]
----
@RestController
class ThisWillActuallyRun {

@RequestMapping("/")
String home() {
return "Hello World!"
}

}
----

NOTE: It doesn't matter where the file is. You can even fit an application that small inside a https://twitter.com/rob_winch/status/364871658483351552[single tweet]!

Next, https://github.com/spring-projects/spring-boot#installing-the-cli[install Spring Boot's CLI].

Run it as follows:

----
$ spring run app.groovy
----

NOTE: This assumes you shut down the previous application, to avoid a port collision.

From a different terminal window:
----
$ curl localhost:8080
Hello World!
----

Spring Boot does this by dynamically adding key annotations to your code and leveraging http://groovy.codehaus.org/Grape[Groovy Grapes] to pull down needed libraries 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. Checkout http://projects.spring.io/spring-boot/docs/README.html[Spring Boot's README]
if you want to dig deeper.