Spring Boot教程:構建springboot工程
簡介
Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。用我的話來理解,就是spring boot其實不是什麼新的框架,它默認配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架(不知道這樣比喻是否合適)
建構工程
你需要:
jdk 1.8或以上
maven 3.0+
STS
打開Idea-> new Project ->Spring starter project->填寫group、artifact ->鉤上web(開啓web功能)->點下一步就行了。
工程目錄
創建完工程,工程的目錄結構如下:
- src
-main
-java
-package
-SpringbootApplication
-resouces
- statics
- templates
- application.yml
-test - pom文件爲基本的依賴管理文件
- resouces 資源文件
- statics 靜態資源
- templates 模板資源
- application.yml 配置文件
- SpringbootApplication程序的入口。
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>firstspringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>firstspringboot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.17.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
其中spring-boot-starter-web不僅包含spring-boot-starter,還自動開啓了web功能。
舉個例子,建個controller:
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/hi")
public String index() {
return "frist Spring Boot!";
}
}
神奇之處:
- 你沒有做任何的web.xml配置。
- 你沒有做任何的sping mvc的配置; springboot爲你做了。
- 你沒有配置tomcat ;springboot內嵌tomcat.
啓動springboot 方式
mvn spring-boot: run 啓動
@SpringBootApplication
public class SpringbootFirstApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFirstApplication.class, args);
}
運行它會先開啓sprigboot工程,然後再測試,localhost:8080/hi測試通過 .