引言
作为多年的 Java 成猿,在 Spring 扫荡 Java 界的时代,不可避免的被长长的 …ApplicationContext.xml 刷屏。更可悲的是不管被刷过多少屏,被虐过多少次,依然没法记住那长长的配置项。
终于,在配置深坑苦苦煎熬之后,有人垂下了一根绳索,带来了 Spring Boot。
Spring Boot充分利用了 JavaConfig 配置模式以及“约定优于配置”的理念,能够极大的简化基于 Spring 的应用开发。为了简化依赖图,Boot 的功能是模块化的,通过导入 Boot 所谓的“starter” 模块,可以将许多的依赖添加到工程之中。
下面,我们就使用 IDEA 和 Gradle 构建一个最简单的 SpringMVC 应用。
Hello MVC
创建一个基于 Gradle 的 Java Web 应用

创建之后,代码结构如下:

添加 Spring Boot Web 依赖
build.gradle 内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| group 'li.fyun' version '1.0-SNAPSHOT'
apply plugin: 'java' apply plugin: 'war' apply plugin: 'idea' apply plugin: 'spring-boot'
sourceCompatibility = 1.8 targetCompatibility = 1.8
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE") } }
jar { baseName = 'springboot' version = '0.1.0' }
repositories { mavenCentral() }
dependencies { compile("org.springframework.boot:spring-boot-starter-web") }
|
打个招呼吧
Application.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package li.fyunli.springboot;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer;
* Created by fyunli on 16/4/1. */ @SpringBootApplication public class Application extends SpringBootServletInitializer {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { application.listeners(); return application.sources(applicationClass); }
private static Class<Application> applicationClass = Application.class;
}
|
HelloController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package li.fyunli.springboot.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
* Created by fyunli on 16/4/1. */ @Controller public class HelloController {
@RequestMapping("/hello") @ResponseBody public String hello(){ return "Hello Boot!"; }
}
|
展示成果
运行 Application.java, 控制台很友好地告知这是基于 Spring Boot 的应用:
1 2 3 4 5 6 7 8 9 10
| ... . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.3.3.RELEASE)
......
|
浏览器访问 http://localhost:8080/hello, 显示:

OK, 第一个 Spring Boot MVC 程序完成。
源代码可以在 github 找到。
修改配置
Spring Boot 可以方便地通过 application.properties 或者 application.yml 调整默认的配置。
如需要修改应用发布端口和目录,在 src/main/resources 中创建 application.properties, 内容如下:
1 2
| server.port=8081 server.contextPath=/springboot
|
启动后访问 http://localhost:8081/springboot/hello 看看效果吧。