Spring Boot 框架概述

发布于:2025-05-10 ⋅ 阅读:(17) ⋅ 点赞:(0)

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 安装

  1. 从 Maven 官方网站下载最新版本的 Maven
  2. 解压下载的文件到本地目录
  3. 配置环境变量 MAVEN_HOME 和 PATH
  4. 验证 Maven 安装:
bash
mvn -version

Gradle 安装

  1. 从 Gradle 官方网站下载最新版本的 Gradle
  2. 解压下载的文件到本地目录
  3. 配置环境变量 GRADLE_HOME 和 PATH
  4. 验证 Gradle 安装:
bash
gradle -v

3、快速开始

3.1 使用 Spring Initializr 创建项目**

Spring Initializr 是一个基于 Web 的工具,可以帮助你快速创建 Spring Boot 项目骨架。

  1. 访问 Spring Initializr
  2. 配置项目元数据:
    。Project: 选择 Maven Project 或 Gradle Project
    。Language: 选择 Java
    。Spring Boot: 选择合适的版本
    。Group 和 Artifact: 填写项目的包名和名称
  3. 添加依赖:
    。至少添加 “Spring Web” 依赖
    。根据需要添加其他依赖,如 “Spring Data JPA”、“Thymeleaf” 等
  4. 点击 “Generate” 按钮下载项目压缩包
  5. 解压下载的文件到本地目录

3.2 项目结构

使用 Spring Initializr 创建的项目结构通常如下:

plaintext
src/
  main/
    java/
      com/
        example/
          demo/
            DemoApplication.java
    resources/
      application.properties
      static/
      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 提供了多种方式来配置应用属性:

  1. application.properties 文件:位于 src/main/resources 目录下
  2. application.yml 文件:与 application.properties 类似,但使用 YAML 格式
  3. 命令行参数
  4. 环境变量
  5. 自定义配置类

示例 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 教程


网站公告

今日签到

点亮在社区的每一天
去签到