學習完整課程請移步 互聯網 Java 全棧工程師
本節視頻
概述
這里我們使用 Intellij IDEA 來新建一個 Spring Boot 項目。
打開 IDEA -> New Project -> Spring Initializr
填寫項目信息
選擇 Spring Boot 版本及 Web 開發所需的依賴
保存項目到指定目錄
工程目錄結構
創建完成后的工程目錄結構如下:
│ .gitignore
│ pom.xml
│
│
└─src
├─main
│ ├─java
│ │ └─com
│ │ └─funtl
│ │ └─hello
│ │ └─spring
│ │ └─boot
│ │ HelloSpringBootApplication.java
│ │
│ └─resources
│ │ application.properties
│ │
│ ├─static
│ └─templates
└─test
└─java
└─com
└─funtl
└─hello
└─spring
└─boot
HelloSpringBootApplicationTests.java
- .gitignore:Git 過濾配置文件
- pom.xml:Maven 的依賴管理配置文件
- HelloSpringBootApplication.java:程序入口
- resources:資源文件目錄
- static: 靜態資源文件目錄
- templates:模板資源文件目錄
- application.properties:Spring Boot 的配置文件,實際開發中會替換成 YAML 語言配置(application.yml)
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.funtl</groupId>
<artifactId>hello-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hello-spring-boot</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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>
- parent:繼承了 Spring Boot 的 Parent,表示我們是一個 Spring Boot 工程
-
spring-boot-starter-web
:包含了spring-boot-starter
還自動幫我們開啟了 Web 支持
功能演示
我們創建一個 Controller 來演示一下 Spring Boot 的神奇功能
package com.funtl.hello.spring.boot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value = "", method = RequestMethod.GET)
public String sayHi() {
return "Hello Spring Boot";
}
}
啟動 HelloSpringBootApplication
的 main()
方法,瀏覽器訪問 http://localhost:8080 可以看到:
Hello Spring Boot
神奇之處
- 沒有配置 web.xml
- 沒有配置 application.xml,Spring Boot 幫你配置了
- 沒有配置 application-mvc.xml,Spring Boot 幫你配置了
- 沒有配置 Tomcat,Spring Boot 內嵌了 Tomcat 容器