让我们来个简单的“Hello World”web应用吧。
build.gradle
文件
buildscript {
repositories {
jcenter()
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'http://repo.spring.io/milestone' }
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M2'
classpath 'io.spring.gradle:dependency-management-plugin:1.0.0.RELEASE'
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
repositories {
jcenter()
maven { url "http://repo.spring.io/snapshot" }
maven { url "http://repo.spring.io/milestone" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile(
"org.springframework.boot:spring-boot-starter-test",
"junit:junit:4.12"
)
}
group 'com.ubicycle'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
Java代码
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
Example
类上的第一个注解是@RestController
,你看代码时的一个提示,对Spring来说,是个特殊的角色。这个例子里,我们的类是一个web@Controller
所以当有http请求进来时,Spring会考虑用它处理。
@RequestMapping
提供路由信息,它告诉Spring任何以/
为路径的http请求会被映射到home
方法上。@RestController
让Spring直接将String结果返回给请求者。
@RestController
和@RequestMapping
都是Spring MVC的注解,不是Spring Boot 特有的注解。
@EnableAutoConfiguration注解
第二个类级别注解是@EnableAutoConfiguration
。这个注解会让Spring Boot基于你加到依赖里的jar包“猜”你会怎么样配置Spring。就像加入spring-boot-starter-web
加入了Tomcat和Spring MVC,自动配置会认为你在部署一个web服务器和相应的Spring。
Starters 和 自动配置
自动配置和Starter是好基友(配合),但这两个概念又不是直接关联的。你可以自由的选择Starter以外的依赖包,Spring Boot依然会将自动配置程序做到最好。
main方法
程序的最后一部分是main
方法。这只是一个标准的遵循java规范的程序入口。通过运行这个main方法代表的是Spring Boot的SpringApplication类。SpringApplication会启动程序,在自动配置的Tomcat web服务器里启动Spring。我们需要将Example.class
作为参数来运行方法告诉SpringApplication谁是主要的Spring组件。args array也会传递任何通过命令行设置的参数。
运行程序
此刻是时候运行我们的程序了。因为我们使用了spring-boot-starter-parent
POM,我们就已经有了好使的运行目标让我们可以启动程序。在项目的根目录里执行gradle bootRun
启动应用:
$ gradle bootRun
:compileJava
:processResources NO-SOURCE
:classes
:bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.M2)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)
打开浏览器输入localhost:8080
,就会看到下面的输出:
Hello World!
按ctrl-c
就可以退出程序