README.md 21.5 KB
Newer Older
R
Roy Clarkson 已提交
1
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.
2 3 4

What you'll build
-----------------
R
Roy Clarkson 已提交
5
You'll build a simple web application with Spring Boot and add some useful services to it.
6 7 8 9 10 11 12

What you'll need
----------------

 - About 15 minutes
 - A favorite text editor or IDE
 - [JDK 6][jdk] or later
G
Greg Turnquist 已提交
13
 - [Gradle 1.8+][gradle] or [Maven 3.0+][mvn]
14
 - You can also import the code from this guide as well as view the web page directly into [Spring Tool Suite (STS)][gs-sts] and work your way through it from there.
15 16

[jdk]: http://www.oracle.com/technetwork/java/javase/downloads/index.html
G
Greg Turnquist 已提交
17
[gradle]: http://www.gradle.org/
18
[mvn]: http://maven.apache.org/download.cgi
19
[gs-sts]: /guides/gs/sts
20 21 22 23 24 25 26 27 28 29

How to complete this guide
--------------------------

Like all Spring's [Getting Started guides](/guides/gs), you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To **start from scratch**, move on to [Set up the project](#scratch).

To **skip the basics**, do the following:

G
Greg Turnquist 已提交
30
 - [Download][zip] and unzip the source repository for this guide, or clone it using [Git][u-git]:
31
`git clone https://github.com/spring-guides/gs-spring-boot.git`
32
 - cd into `gs-spring-boot/initial`.
33
 - Jump ahead to [Learn what you can do with Spring Boot](#initial).
34 35

**When you're finished**, you can check your results against the code in `gs-spring-boot/complete`.
36
[zip]: https://github.com/spring-guides/gs-spring-boot/archive/master.zip
G
Greg Turnquist 已提交
37
[u-git]: /understanding/Git
38 39 40 41 42 43


<a name="scratch"></a>
Set up the project
------------------

G
Greg Turnquist 已提交
44
First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with [Gradle](http://gradle.org) and [Maven](https://maven.apache.org) is included here. If you're not familiar with either, refer to [Building Java Projects with Gradle](/guides/gs/gradle/) or [Building Java Projects with Maven](/guides/gs/maven).
45 46 47 48 49 50 51 52 53 54

### Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with `mkdir -p src/main/java/hello` on *nix systems:

    └── src
        └── main
            └── java
                └── hello

G
Greg Turnquist 已提交
55

G
Greg Turnquist 已提交
56
### Create a Gradle build file
57
Below is the [initial Gradle build file](https://github.com/spring-guides/gs-spring-boot/blob/master/initial/build.gradle). But you can also use Maven. The pom.xml file is included [right here](https://github.com/spring-guides/gs-spring-boot/blob/master/initial/pom.xml). If you are using [Spring Tool Suite (STS)][gs-sts], you can import the guide directly.
G
Greg Turnquist 已提交
58 59 60 61 62

`build.gradle`
```gradle
buildscript {
    repositories {
63
        maven { url "http://repo.spring.io/libs-snapshot" }
G
Greg Turnquist 已提交
64 65 66
        mavenLocal()
    }
    dependencies {
67
        classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M5")
G
Greg Turnquist 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
83
    maven { url "http://repo.spring.io/libs-snapshot" }
G
Greg Turnquist 已提交
84 85 86
}

dependencies {
87
    compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M5")
G
Greg Turnquist 已提交
88 89 90 91
    testCompile("junit:junit:4.11")
}

task wrapper(type: Wrapper) {
G
Greg Turnquist 已提交
92
    gradleVersion = '1.8'
G
Greg Turnquist 已提交
93
}
94
```
G
Greg Turnquist 已提交
95
    
96
[gs-sts]: /guides/gs/sts    
97

98 99
Learn what you can do with Spring Boot
--------------------------------------
100

101
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.
102 103

For example:
104 105 106 107
- 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.
- Doing multipart file uploads? [MultipartConfigElement](http://docs.oracle.com/javaee/6/api/javax/servlet/MultipartConfigElement.html) is part of the servlet 3.0 spec and lets you define upload parameters in pure Java. With Spring Boot, you don't have to plug a MultipartConfigElement into your servlet. Just define one in your application context and Spring Boot will plug it into Spring MVC's battle-tested `DispatcherServlet`.
108

G
Greg Turnquist 已提交
109
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.
110

111 112 113
> **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
114
---------------------------------
115
Now you can create a web controller for a simple web application.
116 117 118 119 120

`src/main/java/hello/HelloController.java`
```java
package hello;

121
import org.springframework.web.bind.annotation.RestController;
122 123
import org.springframework.web.bind.annotation.RequestMapping;

124
@RestController
125
public class HelloController {
126 127
    
    @RequestMapping("/")
128
    public String index() {
129 130 131
        return "Greetings from Spring Boot!";
    }
    
132 133 134
}
```
    
135
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.
136

137 138 139
Create an Application class
---------------------------
Here you create an `Application` class with the components:
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

`src/main/java/hello/Application.java`
```java
package hello;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
157 158 159 160 161 162 163 164 165 166 167 168
    
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        System.out.println("Let's inspect the beans provided by Spring Boot:");
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
169 170 171 172

}
```
    
G
Greg Turnquist 已提交
173
- `@Configuration` tags the class as a source of bean definitions for the application context.
174
- `@EnableAutoConfiguration` tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
175
- 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`.
176 177
- `@ComponentScanning` tells Spring to look for other components, configurations, and services in the the `hello` package, allowing it to find the `HelloController`.

G
Greg Turnquist 已提交
178 179 180
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.
181

182 183 184
Run the application
-------------------
To run the application, execute:
185 186

```sh
G
Greg Turnquist 已提交
187
$ ./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar
188 189
```

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

```sh
$ mvn package && java -jar target/gs-spring-boot-0.1.0.jar
```

196 197
You should see some output like this:

198
```
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
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.

```sh
$ curl localhost:8080
Greetings from Spring Boot!
```

245 246 247
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!
248

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

G
Greg Turnquist 已提交
251
```groovy
G
Greg Turnquist 已提交
252
    compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M4") {
253 254
        exclude module: "spring-boot-starter-tomcat"
    }
G
Greg Turnquist 已提交
255
    compile("org.springframework.boot:spring-boot-starter-jetty:0.5.0.M4")
256 257
```

258
If you are using Maven, the changes look like this:
G
Greg Turnquist 已提交
259 260

```xml
261 262 263 264 265 266 267 268 269 270
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
G
Greg Turnquist 已提交
271 272 273 274 275 276
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
```

277 278 279
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:
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

`src/main/java/hello/Application.java`
```java
package hello;

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
297 298 299 300 301 302 303 304 305 306 307 308
    
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        System.out.println("Let's inspect the beans provided by Spring Boot:");
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
309 310 311 312 313

}
```
    

314 315
Re-run the application
----------------------
316 317 318 319

Run the app again:

```sh
G
Greg Turnquist 已提交
320
$ ./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar
321 322
```

G
Greg Turnquist 已提交
323 324 325 326 327 328
If you are using Maven, execute:

```sh
$ mvn package && java -jar target/gs-spring-boot-0.1.0.jar
```

329 330
Now check out the output:

331
```
332 333 334 335 336 337
Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
338 339
faviconHandlerMapping
faviconRequestHandler
340 341
handlerExceptionResolver
helloController
342
hiddenHttpMethodFilter
343 344 345 346 347 348 349 350 351 352 353 354
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
355 356 357
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
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
```

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

377
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.
378

G
Greg Turnquist 已提交
379
Add production-grade services
380
------------------------------
381
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 [actuator module][spring-boot-actuator], such as health, audits, beans, and more.
382

G
Greg Turnquist 已提交
383 384 385
Add this to your build file's list of dependencies:

```groovy
G
Greg Turnquist 已提交
386
    compile("org.springframework.boot:spring-boot-starter-actuator:0.5.0.M4")
387 388
```

G
Greg Turnquist 已提交
389 390 391 392 393 394 395 396 397
If you are using Maven, add this to your list of dependencies:

```xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
```

398 399 400
Then restart the app:

```sh
G
Greg Turnquist 已提交
401
$ ./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar
402 403
```

G
Greg Turnquist 已提交
404 405 406 407 408 409
If you are using Maven, execute:

```sh
$ mvn package && java -jar target/gs-spring-boot-0.1.0.jar
```

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

412
```
413 414 415 416 417 418 419 420 421 422
2013-08-01 08:03:42.592  INFO 43851 ... Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.Map<java.lang.String, java.lang.Object> 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]
423 424
```

425 426 427 428 429 430 431 432
They include: errors, [environment](http://localhost:8080/env), [health](http://localhost:8080/health), [beans](http://localhost:8080/beans), [info](http://localhost:8080/info), [metrics](http://localhost:8080/metrics), [trace](http://localhost:8080/trace), [dump](http://localhost:8080/dump), and shutdown.

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

```sh
$ curl localhost:8080/health
ok
```
433 434 435 436 437 438 439

You can invoke shutdown through curl.

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

440
The response shows that shutdown through REST is currently disabled by default:
441 442 443 444
```sh
{"message":"Shutdown not enabled, sorry."}
```

G
Greg Turnquist 已提交
445
Whew! You probably don't want that until you are ready to turn on proper security settings, if at all.
446

G
Greg Turnquist 已提交
447
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.
448 449

View Spring Boot's starters
G
Greg Turnquist 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463
----------------------
You have seen some of Spring Boot's **starters**. Here is a complete list:
- spring-boot-starter-actuator
- spring-boot-starter-batch
- spring-boot-starter-data-jpa
- spring-boot-starter-integration
- spring-boot-starter-jetty
- spring-boot-starter-logging
- spring-boot-starter-parent
- spring-boot-starter-security
- spring-boot-starter-tomcat
- spring-boot-starter-web


464 465 466
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.
467

468
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 已提交
469

470
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 已提交
471

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

```groovy
475
@RestController
476 477 478 479 480 481 482 483 484
class ThisWillActuallyRun {

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

}
```
G
Greg Turnquist 已提交
485

G
Greg Turnquist 已提交
486
> **Note:** It doesn't matter where the file is. You can even fit an application that small inside a [single tweet](https://twitter.com/rob_winch/status/364871658483351552)!
487

488
Next, [install Spring Boot's CLI](https://github.com/spring-projects/spring-boot#installing-the-cli).
G
Greg Turnquist 已提交
489

490
Run it as follows:
491

G
Greg Turnquist 已提交
492
```sh
493
$ spring run app.groovy
494 495
```

G
Greg Turnquist 已提交
496 497
> **Note:** This assumes you shut down the previous application, to avoid a port collision.

498 499
From a different terminal window:
```sh
500 501 502 503
$ curl localhost:8080
Hello World!
```

504
Spring Boot does this by dynamically adding key annotations to your code and leveraging [Groovy Grapes](http://groovy.codehaus.org/Grape) to pull down needed libraries to make the app run.
G
Greg Turnquist 已提交
505

506
Summary
507
----------------
G
Greg Turnquist 已提交
508
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.
509

510 511
[spring-boot]: https://github.com/spring-projects/spring-boot
[spring-boot-actuator]: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-actuator/README.md
512
[gs-uploading-files]: /guides/gs/uploading-files