1. 簡介
Spring Boot 是由 Pivotal 團隊開發的一個用于簡化 Spring 應用開發的框架。它通過提供默認配置、嵌入式服務器和自動配置等特性,讓開發者能夠更快速地構建獨立的、生產級別的 Spring 應用。
Spring Boot 的主要特點包括:
- 快速創建獨立的 Spring 應用
- 內嵌 Tomcat、Jetty 或 Undertow 等服務器
- 提供 “starter” 依賴簡化構建配置
- 自動配置 Spring 和第三方庫
- 提供生產就緒型特性,如指標監控、健康檢查等
- 無需 XML 配置
2. 環境準備
2.1 JDK 安裝
Spring Boot 要求 JDK 8 或更高版本。你可以從 Oracle 官方網站或 OpenJDK 下載并安裝適合你操作系統的 JDK。
安裝完成后,驗證 JDK 版本:
bash
java -version
2.2 Maven 或 Gradle 安裝
Spring Boot 項目可以使用 Maven 或 Gradle 進行構建。
Maven 安裝
- 從 Maven 官方網站下載最新版本的 Maven
- 解壓下載的文件到本地目錄
- 配置環境變量 MAVEN_HOME 和 PATH
- 驗證 Maven 安裝:
bash
mvn -version
Gradle 安裝
- 從 Gradle 官方網站下載最新版本的 Gradle
- 解壓下載的文件到本地目錄
- 配置環境變量 GRADLE_HOME 和 PATH
- 驗證 Gradle 安裝:
bash
gradle -v
3、快速開始
3.1 使用 Spring Initializr 創建項目**
Spring Initializr 是一個基于 Web 的工具,可以幫助你快速創建 Spring Boot 項目骨架。
- 訪問 Spring Initializr
- 配置項目元數據:
。Project: 選擇 Maven Project 或 Gradle Project
。Language: 選擇 Java
。Spring Boot: 選擇合適的版本
。Group 和 Artifact: 填寫項目的包名和名稱 - 添加依賴:
。至少添加 “Spring Web” 依賴
。根據需要添加其他依賴,如 “Spring Data JPA”、“Thymeleaf” 等 - 點擊 “Generate” 按鈕下載項目壓縮包
- 解壓下載的文件到本地目錄
3.2 項目結構
使用 Spring Initializr 創建的項目結構通常如下:
plaintext
src/main/java/com/example/demo/DemoApplication.javaresources/application.propertiesstatic/templates/test/java/com/example/demo/DemoApplicationTests.java
pom.xml 或 build.gradle
3.3 第一個 Spring Boot 應用
下面是一個簡單的 Spring Boot Web 應用示例:
java
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);
}@GetMapping("/hello")
public String hello() {return "Hello, Spring Boot!";
}
}
這個應用包含:
- @SpringBootApplication 注解:標識這是一個 Spring Boot 應用
- main 方法:應用的入口點,啟動 Spring Boot 應用
- @RestController 注解:標識這是一個 RESTful 控制器
- @GetMapping 注解:處理 HTTP GET 請求
3.4 運行應用
你可以通過以下方式運行 Spring Boot 應用:
使用命令行
在項目根目錄下執行:
bash
mvn spring-boot:run
或
bash
gradle bootRun
使用 IDE
在 IDE 中打開項目,找到 DemoApplication 類,運行其 main 方法。
應用啟動后,訪問 http://localhost:8080/hello,你應該能看到 “Hello, Spring Boot!” 的響應。
4. 核心特性
4.1 自動配置
Spring Boot 的自動配置是其核心特性之一。它根據你項目中添加的依賴和配置,自動配置 Spring 應用的各種組件。
例如,如果你添加了 “Spring Data JPA” 依賴,Spring Boot 會自動配置一個 DataSource 和 JPA 實體管理器。
你可以通過 @SpringBootApplication 注解啟用自動配置,該注解包含了 @EnableAutoConfiguration 注解。
如果你想禁用某些自動配置,可以使用 @SpringBootApplication 的 exclude 屬性:
java
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {// ...
}
4.2 Starter 依賴
Spring Boot 的 Starter 依賴是一組方便的依賴描述符,你可以將它們添加到項目中。你只需要添加所需的 Starter,Spring Boot 會自動處理所有相關依賴。
常見的 Starter 依賴包括:
- spring-boot-starter-web: 構建 Web 應用,包括 RESTful 服務
- spring-boot-starter-data-jpa: 使用 JPA 進行數據庫訪問
- spring-boot-starter-security: 添加 Spring Security 安全功能
- spring-boot-starter-test: 用于測試 Spring Boot 應用
- spring-boot-starter-thymeleaf: 使用 Thymeleaf 模板引擎
4.3 嵌入式服務器
Spring Boot 支持嵌入式服務器,這意味著你不需要部署 WAR 文件到外部服務器,而是可以將應用打包成一個可執行的 JAR 文件,其中包含嵌入式服務器。
默認情況下,Spring Boot 使用 Tomcat 作為嵌入式服務器。你可以通過添加相應的依賴來切換到 Jetty 或 Undertow:
xml
<!-- 使用 Jetty 替代 Tomcat -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></exclusion></exclusions>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
4.4 配置屬性
Spring Boot 提供了多種方式來配置應用屬性:
- application.properties 文件:位于 src/main/resources 目錄下
- application.yml 文件:與 application.properties 類似,但使用 YAML 格式
- 命令行參數
- 環境變量
- 自定義配置類
示例 application.properties 文件:
properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
你可以通過 @Value 注解或 @ConfigurationProperties 注解來注入配置屬性:
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class MyConfig {@Value("${server.port}")private int port;// getter 和 setter
}
5. 數據訪問
Spring Boot 提供了多種數據訪問方式,包括 JDBC、JPA 和 NoSQL 等。
5.1 使用 Spring Data JPA
Spring Data JPA 是訪問關系型數據庫的推薦方式。它簡化了 JPA 的使用,提供了豐富的 Repository 接口。
以下是使用 Spring Data JPA 的基本步驟:
添加依賴:
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope>
</dependency>
定義實體類:
java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;// 構造方法、getter 和 setter
}
創建 Repository 接口:
java
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository<User, Long> {// 可以添加自定義查詢方法User findByName(String name);
}
使用 Repository:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;@Component
public class DataLoader implements CommandLineRunner {
private final UserRepository userRepository;@Autowired
public DataLoader(UserRepository userRepository) {this.userRepository = userRepository;
}@Override
public void run(String... args) throws Exception {userRepository.save(new User("John Doe", "john@example.com"));userRepository.save(new User("Jane Doe", "jane@example.com"));
}
}
5.2 使用 JDBC Template
如果你更喜歡使用 JDBC,可以使用 Spring 的 JdbcTemplate:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;@Repository
public class UserJdbcRepository {
private final JdbcTemplate jdbcTemplate;@Autowired
public UserJdbcRepository(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;
}public User findById(Long id) {return jdbcTemplate.queryForObject("SELECT * FROM users WHERE id = ?",(rs, rowNum) -> new User(rs.getLong("id"),rs.getString("name"),rs.getString("email")),id);
}
}
6. Web 開發
Spring Boot 提供了強大的 Web 開發支持,包括 RESTful 服務和 Web 應用開發。
6.1 RESTful 服務
以下是一個簡單的 RESTful 控制器示例:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;@Autowired
public UserController(UserRepository userRepository) {this.userRepository = userRepository;
}@GetMapping
public List<User> findAll() {return userRepository.findAll();
}@GetMapping("/{id}")
public User findById(@PathVariable Long id) {return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
}@PostMapping
public User save(@RequestBody User user) {return userRepository.save(user);
}@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {userRepository.deleteById(id);
}
}
6.2 視圖模板
Spring Boot 支持多種視圖模板引擎,如 Thymeleaf、Freemarker 和 JSP 等。
以下是使用 Thymeleaf 的示例:
添加依賴:
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
創建控制器:
java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {model.addAttribute("message", "Welcome to Spring Boot!");return "home";
}
}
創建 Thymeleaf 模板文件 src/main/resources/templates/home.html:
html
預覽
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Home Page</title>
</head>
<body><h1 th:text="${message}">Default Message</h1>
</body>
</html>
7. 安全 Spring Boot 集成了 Spring Security 提供強大的安全功能
7.1 添加安全依賴
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加此依賴后,Spring Boot 會自動配置基本的安全策略,所有 HTTP 端點都會被保護,需要進行身份驗證才能訪問。
7.2 自定義安全配置
你可以通過創建一個配置類來自定義安全配置:
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();return http.build();
}@Bean
public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
}
}
這個配置類做了以下事情:
允許訪問 /public/** 路徑下的資源
要求所有其他請求進行身份驗證
自定義登錄頁面
配置密碼編碼器
8. 測試
Spring Boot 提供了豐富的測試支持,包括集成測試和單元測試。
8.1 添加測試依賴
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
8.2 單元測試示例
java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;@MockBean
private UserRepository userRepository;@Test
public void testFindByName() {User user = new User("John Doe", "john@example.com");when(userRepository.findByName("John Doe")).thenReturn(user);User result = userService.findByName("John Doe");assertEquals("John Doe", result.getName());
}
}
8.3 Web 集成測試示例
java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;@Test
public void testFindAll() throws Exception {mockMvc.perform(get("/api/users")).andExpect(status().isOk()).andExpect(content().contentType("application/json"));
}
}
9. 部署
Spring Boot 應用可以以多種方式部署:
9.1 作為可執行 JAR 部署
這是最常見的部署方式。將應用打包成一個可執行的 JAR 文件,包含所有依賴和嵌入式服務器:
bash
mvn clean package
java -jar target/myapp-0.0.1-SNAPSHOT.jar
9.2 部署到外部服務器
如果你想部署到外部服務器,需要將項目打包成 WAR 文件:
修改 pom.xml 或 build.gradle,將打包方式改為 WAR
排除嵌入式 Tomcat 依賴
添加 Servlet API 依賴
創建一個 ServletInitializer 類
示例 ServletInitializer 類:
java
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(DemoApplication.class);
}
}
9.3 Docker 容器部署
將 Spring Boot 應用打包到 Docker 容器中是一種流行的部署方式:
創建 Dockerfile:
dockerfile
FROM openjdk:17-jdk-slim
COPY target/myapp-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT [“java”,“-jar”,“/app.jar”]
構建 Docker 鏡像:
bash
docker build -t myapp .
運行 Docker 容器:
bash
docker run -p 8080:8080 myapp
10. 生產就緒特性
Spring Boot 提供了許多生產就緒特性,幫助你監控和管理應用:
10.1 Actuator
Spring Boot Actuator 提供了生產就緒端點,幫助你監控和管理應用:
添加依賴:
xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
常用端點:
/actuator/health:應用健康狀態
/actuator/info:應用信息
/actuator/metrics:應用指標
/actuator/loggers:日志配置
/actuator/env:環境變量
10.2 自定義健康檢查
你可以通過實現 HealthIndicator 接口來添加自定義健康檢查:
java
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health() {// 執行健康檢查boolean isHealthy = checkSystem();if (isHealthy) {return Health.up().build();} else {return Health.down().withDetail("Error", "System is not healthy").build();}
}private boolean checkSystem() {// 實現健康檢查邏輯return true;
}
}
11. 總結
Spring Boot 是一個強大的框架,它大大簡化了 Spring 應用的開發過程。通過自動配置、Starter 依賴和嵌入式服務器等特性,開發者可以更快速地構建和部署生產級別的應用。
本文介紹了 Spring Boot 的基本概念、核心特性、數據訪問、Web 開發、安全、測試、部署以及生產就緒特性等方面的內容。希望這些信息對你學習和使用 Spring Boot 有所幫助。
12. 參考資料
Spring Boot 官方文檔
Spring 官方網站
Spring Boot 實戰
Spring Boot 教程