Spring Boot 简介
使用Spring Boot可以轻松创建生产级别的Spring应用程序,大多数Spring Boot应用仅需要少许的Spring配置。 可以使用Spring Boot创建Java程序,然后使用 java -jar运行,或者是直接打成war包,放到容器中运行。
系统要求
Spring Boot 2.0.1.RELEASE 需要使用Java8或者Java8,Spring Framework 5.0.5.RELEASE 或者它的后续版本。构建工具,Maven需要3.2以上版本,需要使用Gradle 4. Spring Boot 内置的Servlet容器,Servlet的版本为3.1,支持Tomcat 8.5,Jetty 9.4,Undertow 1.4
安装Spring Boot
Spring Boot的依赖都是以org.springframework.boot为groupId的,其artifictId 则是以spring-boot-starter开头,例如如下pom.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
如果使用Gradle,配置如下
plugins {
id 'org.springframework.boot' version '2.0.1.RELEASE'
id 'java'
}
jar {
baseName = 'myproject'
version = '0.0.1-SNAPSHOT'
}
repositories {
jcenter()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
开发第一个Spring Boot程序
pom.xml 文件使用上述配置即可,现在编写其配置文件和Controller,例如Example.java
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
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);
}
}
@RestController表示Example是一个Controller,可以接受请求 @EnableAutoConfiguration 表示根据添加的jar依赖自动配置Spring应用,因为添加了spring-boot-starter-web依赖,所以默认会配置Tomcat和SpringMVC。 对于main方法,SpringApplication通过调用run方法启动Spring应用,args则是通过命令行参数,传递给Spring。
运行如下:
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.1.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)