README.adoc 13.6 KB
Newer Older
1
:spring_boot_version: 2.2.1.RELEASE
G
Greg Turnquist 已提交
2 3 4 5 6 7
: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.
J
Jay Bryant 已提交
8
It is meant to give you a quick taste of Spring Boot. If you want to create your own Spring Boot-based project, visit
9 10
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.
G
Greg Turnquist 已提交
11 12

== What you'll build
B
Beverley Talbott 已提交
13
You'll build a simple web application with Spring Boot and add some useful services to it.
14

G
Greg Turnquist 已提交
15 16
== What you'll need

G
Greg Turnquist 已提交
17
:java_version: 1.8
G
Greg Turnquist 已提交
18
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[]
19

G
Greg Turnquist 已提交
20
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[]
21 22


23
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-gradle.adoc[]
24

25
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-maven.adoc[]
26

27
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-sts.adoc[]
28

G
Greg Turnquist 已提交
29
== Learn what you can do with Spring Boot
30

31
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.
32 33

For example:
G
Greg Turnquist 已提交
34

35 36 37
- 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.
38

G
Greg Turnquist 已提交
39
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.
40

G
Greg Turnquist 已提交
41
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.
42

G
Greg Turnquist 已提交
43
== Create a simple web application
44
Now you can create a web controller for a simple web application.
45

G
Greg Turnquist 已提交
46
`src/main/java/hello/HelloController.java`
47
[source,java,tabsize=2]
G
Greg Turnquist 已提交
48 49 50
----
include::initial/src/main/java/hello/HelloController.java[]
----
J
Jay Bryant 已提交
51

52
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.
53

G
Greg Turnquist 已提交
54
== Create an Application class
55
Here you create an `Application` class with the components:
56

G
Greg Turnquist 已提交
57
`src/main/java/hello/Application.java`
58
[source,java,tabsize=2]
G
Greg Turnquist 已提交
59
----
G
Greg Turnquist 已提交
60
include::complete/src/main/java/hello/Application.java[]
G
Greg Turnquist 已提交
61
----
D
Dave Syer 已提交
62

63
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/spring-boot-application.adoc[]
G
Greg Turnquist 已提交
64

D
Dave Syer 已提交
65
There is also a `CommandLineRunner` method marked as a `@Bean` and this runs on start up. It 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.
66

G
Greg Turnquist 已提交
67
== Run the application
68
To run the application, execute:
69

70
[subs="attributes"]
G
Greg Turnquist 已提交
71 72 73
----
./gradlew build && java -jar build/libs/{project_id}-0.1.0.jar
----
74

G
Greg Turnquist 已提交
75 76
If you are using Maven, execute:

77
[subs="attributes"]
G
Greg Turnquist 已提交
78 79 80
----
mvn package && java -jar target/{project_id}-0.1.0.jar
----
G
Greg Turnquist 已提交
81

82 83
You should see some output like this:

G
Greg Turnquist 已提交
84
....
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
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
G
Greg Turnquist 已提交
120
....
121 122 123 124 125

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

Check out the service.

G
Greg Turnquist 已提交
126
....
127 128
$ curl localhost:8080
Greetings from Spring Boot!
G
Greg Turnquist 已提交
129
....
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
== Add Unit Tests

You will want to add a test for the endpoint you added, and Spring Test already provides some machinery for that, and it's easy to include in your project.

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

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

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

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

Now write a simple unit test that mocks the servlet request and response through your endpoint:

`src/test/java/hello/HelloControllerTest.java`
152
[source,java,tabsize=2]
153
----
G
Greg Turnquist 已提交
154
include::complete/src/test/java/hello/HelloControllerTest.java[]
155 156
----

D
Dave Syer 已提交
157
The `MockMvc` comes from Spring Test and allows you, via a set of convenient builder classes, to send HTTP requests into the `DispatcherServlet` and make assertions about the result. Note the use of the `@AutoConfigureMockMvc` together with `@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 using the `@WebMvcTest`. Spring Boot automatically tries to locate the main application class of your application in either case, but you can override it, or narrow it down, if you want to build something different.
158 159 160

As well as mocking the HTTP request cycle we can also use Spring Boot to write a very simple full-stack integration test. For example, instead of (or as well as) the mock test above we could do this:

G
Greg Turnquist 已提交
161
`src/test/java/hello/HelloControllerIT.java`
162
[source,java,tabsize=2]
163
----
G
Greg Turnquist 已提交
164
include::complete/src/test/java/hello/HelloControllerIT.java[]
165 166
----

D
Dave Syer 已提交
167
The embedded server is started up on a random port by virtue of the `webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT` and the actual port is discovered at runtime with the `@LocalServerPort`.
168

G
Greg Turnquist 已提交
169
== Add production-grade services
170
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 http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#production-ready[actuator module], such as health, audits, beans, and more.
171

G
Greg Turnquist 已提交
172 173
Add this to your build file's list of dependencies:

G
Greg Turnquist 已提交
174 175
[source,groovy]
----
G
Greg Turnquist 已提交
176
include::complete/build.gradle[tag=actuator]
G
Greg Turnquist 已提交
177
----
178

G
Greg Turnquist 已提交
179 180
If you are using Maven, add this to your list of dependencies:

G
Greg Turnquist 已提交
181 182
[source,xml]
----
G
Greg Turnquist 已提交
183
include::complete/pom.xml[tag=actuator]
G
Greg Turnquist 已提交
184
----
G
Greg Turnquist 已提交
185

186 187
Then restart the app:

G
Greg Turnquist 已提交
188 189 190 191
[subs="attributes"]
----
./gradlew build && java -jar build/libs/{project_id}-0.1.0.jar
----
192

G
Greg Turnquist 已提交
193 194
If you are using Maven, execute:

G
Greg Turnquist 已提交
195 196 197 198
[subs="attributes"]
----
mvn package && java -jar target/{project_id}-0.1.0.jar
----
G
Greg Turnquist 已提交
199

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

G
Greg Turnquist 已提交
202
....
203 204 205 206 207 208 209 210
2018-03-17 15:42:20.088  ... : Mapped "{[/error],produces=[text/html]}" onto public org.s...
2018-03-17 15:42:20.089  ... : Mapped "{[/error]}" onto public org.springframework.http.R...
2018-03-17 15:42:20.121  ... : Mapped URL path [/webjars/**] onto handler of type [class ...
2018-03-17 15:42:20.121  ... : Mapped URL path [/**] onto handler of type [class org.spri...
2018-03-17 15:42:20.157  ... : Mapped URL path [/**/favicon.ico] onto handler of type [cl...
2018-03-17 15:42:20.488  ... : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd...
2018-03-17 15:42:20.490  ... : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.s...
2018-03-17 15:42:20.491  ... : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring...
G
Greg Turnquist 已提交
211
....
212

213
They include: errors, http://localhost:8080/actuator/health[actuator/health], http://localhost:8080/actuator/info[actuator/info], http://localhost:8080/actuator[actuator].
214

215 216
NOTE: There is also a `/actuator/shutdown` endpoint, but it's only visible by default via JMX. To http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#production-ready-endpoints-enabling-endpoints[enable it as an HTTP endpoint], add
`management.endpoints.shutdown.enabled=true` to your `application.properties` file.
217 218 219

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

G
Greg Turnquist 已提交
220
----
221 222
$ curl localhost:8080/actuator/health
{"status":"UP"}
G
Greg Turnquist 已提交
223
----
224

225
You can try to invoke shutdown through curl.
226

G
Greg Turnquist 已提交
227
----
228
$ curl -X POST localhost:8080/actuator/shutdown
229
{"timestamp":1401820343710,"error":"Method Not Allowed","status":405,"message":"Request method 'POST' not supported"}
G
Greg Turnquist 已提交
230
----
231

232
Because we didn't enable it, the request is blocked by the virtue of not existing.
233

234
For more details about each of these REST points and how you can tune their settings with an `application.properties` file (in `src/main/resources`), you can read detailed http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#production-ready-endpoints[docs about the endpoints].
G
Greg Turnquist 已提交
235 236

== View Spring Boot's starters
237
You have seen some of http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#using-boot-starter[Spring Boot's "starters"]. You can see them all https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters[here in source code].
G
Greg Turnquist 已提交
238 239

== JAR support and Groovy support
240
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.
241

242
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`.
G
Greg Turnquist 已提交
243

244
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.
G
Greg Turnquist 已提交
245

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

G
Greg Turnquist 已提交
248 249
[source,groovy]
----
250
@RestController
251 252 253 254 255 256 257 258
class ThisWillActuallyRun {

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

}
G
Greg Turnquist 已提交
259
----
G
Greg Turnquist 已提交
260

G
Greg Turnquist 已提交
261
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]!
262

263
Next, http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#getting-started-installing-the-cli[install Spring Boot's CLI].
G
Greg Turnquist 已提交
264

265
Run it as follows:
266

G
Greg Turnquist 已提交
267
----
268
$ spring run app.groovy
G
Greg Turnquist 已提交
269
----
270

G
Greg Turnquist 已提交
271
NOTE: This assumes you shut down the previous application, to avoid a port collision.
G
Greg Turnquist 已提交
272

273
From a different terminal window:
G
Greg Turnquist 已提交
274
----
275 276
$ curl localhost:8080
Hello World!
G
Greg Turnquist 已提交
277
----
G
Greg Turnquist 已提交
278

D
Dave Syer 已提交
279
Spring Boot does this by dynamically adding key annotations to your code and using http://groovy.codehaus.org/Grape[Groovy Grape] to pull down libraries needed to make the app run.
280

G
Greg Turnquist 已提交
281
== Summary
282
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.
283
This is only a small sampling of what Spring Boot can do. Checkout http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle[Spring Boot's online docs]
284
if you want to dig deeper.
G
Greg Turnquist 已提交
285

J
Jay Bryant 已提交
286 287 288
== See Also

The following guides may also be helpful:
G
Greg Turnquist 已提交
289

J
Jay Bryant 已提交
290 291 292 293
* https://spring.io/guides/gs/securing-web/[Securing a Web Application]
* https://spring.io/guides/gs/serving-web-content/[Serving Web Content with Spring MVC]

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