Spring Boot簡介
spring框架功能很強大,但是就算是一個很簡單的項目,我們也要配置很多東西。因此就有了Spring Boot框架,它的作用很簡單,就是幫我們自動配置。Spring Boot框架的核心就是自動配置,只要存在相應的jar包,Spring就幫我們自動配置。
Spring boot是一個在Spring 的基礎上搭建的全新的微框架,其目的是簡化Spring的搭建和開發過程。
開始搭建
創建項目
根據官方網站上的Quick Start,首先創建一個Maven項目
這裏的Group Id和Artifact Id自己填寫任意的即可,Packaging選擇jar
並且在項目中增加SampleController 類
引入依賴
修改pom文件
<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>cn.edu.cqu</groupId>
<artifactId>SpringBootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
修改java文件
package controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/hello1")
@ResponseBody
String hello1() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
運行項目
在這個java文件中右鍵 Run as -> Java Application。當看到 “Tomcat started on port(s): 8080 (http)” 字樣說明啓動成功。
打開瀏覽器訪問 http://localhost:8080//hello1,結果如下:
熱部署
如果想讓項目在修改類文件後自動重新部署,修改pom.xml文件爲如下之後項目便能實現不用重啓應用達到熱部署
<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>cn.edu.cqu</groupId>
<artifactId>SpringBootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 沒有該配置,devtools 不生效 -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
項目可在GitHub上下載https://github.com/tripleHu/SpringBootDemo