Spring Boot学习知识点大全(一)

简介: 教程来源 https://app-a87ujc988w01.appmiaoda.com/ Spring Boot 是 Spring 家族中革命性框架,秉持“约定优于配置”理念,通过自动配置、起步依赖、嵌入式服务器等特性,大幅简化企业级 Java 应用开发。本文系统梳理其核心概念、注解、多环境配置与最佳实践,助初学者快速入门,为进阶开发者提供深度参考。

Spring Boot 作为 Spring 家族中最具革命性的框架,以其“约定优于配置”的理念,彻底改变了 Java 企业级应用的开发方式。它通过自动配置、起步依赖、嵌入式服务器等特性,让开发者能够快速构建生产级别的 Spring 应用,极大地提升了开发效率。本文将系统全面地梳理 Spring Boot 的核心知识点,从基础概念到高级特性,帮助初学者快速上手,也为有经验的开发者提供深入的技术参考。
20aa7ffe-c7c3-4945-aa92-b639bcf43842.png

一、Spring Boot 概述

1.1 什么是 Spring Boot
Spring Boot 是 Pivotal 团队开发的用于简化 Spring 应用初始搭建和开发过程的框架。它不是对 Spring 功能的增强,而是提供了一种快速使用 Spring 的方式。

核心特性:

自动配置:根据类路径中的依赖自动配置 Spring 应用

起步依赖:提供了一系列 starter POMs,简化 Maven/Gradle 配置

嵌入式服务器:内置 Tomcat、Jetty、Undertow 等服务器

生产就绪:提供健康检查、指标监控、外部化配置等功能

无代码生成和 XML 配置:完全基于注解和 Java 配置

1.2 Spring Boot 与 Spring 的关系

Spring Framework(基础能力)
    ↓
Spring Boot(快速构建)
    ↓
Spring Cloud(分布式解决方案)

Spring Framework 提供核心的 IoC、AOP 等基础能力

Spring Boot 在 Spring 基础上提供快速开发能力

Spring Cloud 基于 Spring Boot 构建微服务解决方案

1.3 环境搭建
Maven 配置:

java
<?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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>17</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Web 起步依赖 -->
        <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>

        <!-- 开发工具(热部署) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- 配置处理器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Gradle 配置:

gradle
plugins {
    id 'org.springframework.boot' version '3.1.5'
    id 'io.spring.dependency-management' version '1.1.3'
    id 'java'
}

group = 'com.example'
version = '1.0.0'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
}

test {
    useJUnitPlatform()
}

1.4 第一个 Spring Boot 应用

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!";
    }
}

启动方式:

# Maven 方式
mvn spring-boot:run

# Java 命令方式
java -jar target/demo-1.0.0.jar

# IDE 方式
直接运行 main 方法

二、核心注解

2.1 @SpringBootApplication

java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// @SpringBootApplication 是三个注解的组合
@SpringBootConfiguration  // 标明这是一个配置类
@EnableAutoConfiguration  // 开启自动配置
@ComponentScan            // 组件扫描
public @interface SpringBootApplication {
}

2.2 常用注解详解

j
// @SpringBootConfiguration
@Configuration
public class AppConfig {
    // 配置类
}

// @EnableAutoConfiguration - 开启自动配置
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application {
    // 排除特定自动配置
}

// @ComponentScan - 组件扫描
@ComponentScan(basePackages = "com.example", 
               excludeFilters = @ComponentScan.Filter(
                   type = FilterType.REGEX,
                   pattern = "com.example.exclude.*"
               ))
public class AppConfig {
}

// @RestController = @Controller + @ResponseBody
@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "张三");
    }
}

// @RequestMapping 的变体
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

// @RequestParam - 获取请求参数
@GetMapping("/search")
public List<User> search(@RequestParam String keyword,
                         @RequestParam(defaultValue = "1") int page,
                         @RequestParam(required = false) Integer size) {
    return userService.search(keyword, page, size);
}

// @PathVariable - 获取路径变量
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
    return userService.findById(id);
}

// @RequestBody - 获取请求体
@PostMapping
public User createUser(@RequestBody User user) {
    return userService.create(user);
}

// @ResponseStatus - 指定响应状态码
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@RequestBody User user) {
    return userService.create(user);
}

// @ExceptionHandler - 异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleBusinessException(BusinessException e) {
        return Result.error(e.getMessage());
    }
}

// @ModelAttribute - 绑定模型属性
@GetMapping("/profile")
public String profile(@ModelAttribute("user") User user) {
    return "profile";
}

// @CrossOrigin - 跨域支持
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class ApiController {
}

// @Validated - 参数校验
@RestController
@Validated
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable @Min(1) Long id) {
        return userService.findById(id);
    }
}

三、配置文件

3.1 application.properties

properties
# 服务器配置
server.port=8080
server.servlet.context-path=/api
server.error.include-stacktrace=always
server.tomcat.max-connections=1000
server.tomcat.max-threads=200
server.tomcat.accept-count=100

# 日志配置
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=logs/application.log
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.connection-timeout=30000

# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql=true

# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=2000ms
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8

# 文件上传配置
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
spring.servlet.multipart.enabled=true

# 国际化配置
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
spring.messages.cache-duration=3600

# 静态资源配置
spring.web.resources.static-locations=classpath:/static/,classpath:/public/
spring.web.resources.cache.period=3600

# 热部署
spring.devtools.restart.enabled=true
spring.devtools.restart.additional-paths=src/main/java
spring.devtools.restart.exclude=static/**,public/**

# Actuator 配置
management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.show-details=always
management.info.env.enabled=true

# 自定义配置
app.name=Spring Boot Demo
app.version=1.0.0
app.description=Spring Boot 学习示例

3.2 application.yml

yaml
# application.yml
server:
  port: 8080
  servlet:
    context-path: /api
    session:
      timeout: 1800s
  tomcat:
    max-connections: 1000
    max-threads: 200
    accept-count: 100

logging:
  level:
    root: INFO
    com.example: DEBUG
  file:
    name: logs/application.log
  pattern:
    console: '%d{yyyy-MM-dd HH:mm:ss} - %msg%n'
    file: '%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      maximum-pool-size: 10
      connection-timeout: 30000

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect
        format_sql: true

  redis:
    host: localhost
    port: 6379
    password: 
    timeout: 2000ms
    jedis:
      pool:
        max-active: 8
        max-idle: 8

  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB
      enabled: true

  messages:
    basename: i18n/messages
    encoding: UTF-8
    cache-duration: 3600

  web:
    resources:
      static-locations: classpath:/static/,classpath:/public/
      cache:
        period: 3600

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus
  endpoint:
    health:
      show-details: always
  info:
    env:
      enabled: true

app:
  name: Spring Boot Demo
  version: 1.0.0
  description: Spring Boot 学习示例

3.3 多环境配置
配置文件结构:

src/main/resources/
├── application.yml              # 主配置文件
├── application-dev.yml          # 开发环境
├── application-test.yml         # 测试环境
├── application-prod.yml         # 生产环境
└── application-local.yml        # 本地环境

application.yml:

yaml
spring:
  profiles:
    active: dev  # 激活开发环境
    include: common  # 包含公共配置

# 通用配置
spring:
  config:
    import: optional:file:./config/  # 导入外部配置

# 多环境配置
---
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 8080
logging:
  level:
    com.example: DEBUG

---
spring:
  config:
    activate:
      on-profile: test
server:
  port: 8081
logging:
  level:
    com.example: INFO

---
spring:
  config:
    activate:
      on-profile: prod
server:
  port: 80
logging:
  level:
    com.example: WARN

启动方式:

# 指定环境
java -jar app.jar --spring.profiles.active=prod

# 使用环境变量
export SPRING_PROFILES_ACTIVE=prod
java -jar app.jar

# Maven 启动
mvn spring-boot:run -Dspring-boot.run.profiles=prod

# 使用外部配置文件
java -jar app.jar --spring.config.location=./config/application.yml

3.4 配置绑定

// @Value 注入
@Component
public class AppConfig {
    @Value("${app.name}")
    private String appName;

    @Value("${app.version:1.0.0}")
    private String version;

    @Value("${server.port}")
    private int port;

    @Value("#{systemProperties['user.name']}")
    private String userName;

    @Value("#{T(java.lang.Math).random() * 100}")
    private double randomNumber;
}

// @ConfigurationProperties 绑定
@ConfigurationProperties(prefix = "app")
@Component
@Data
public class AppProperties {
    private String name;
    private String version;
    private String description;
    private Map<String, String> metadata = new HashMap<>();
    private List<String> tags = new ArrayList<>();

    private Database database = new Database();
    private Redis redis = new Redis();

    @Data
    public static class Database {
        private String url;
        private String username;
        private String password;
        private int maxConnections = 10;
    }

    @Data
    public static class Redis {
        private String host;
        private int port;
        private int timeout = 2000;
    }
}

// 启用配置属性
@EnableConfigurationProperties(AppProperties.class)
@Configuration
public class PropertiesConfig {
}

// 配置文件
app:
  name: Spring Boot Demo
  version: 1.0.0
  description: 示例应用
  metadata:
    author: 张三
    email: zhangsan@example.com
  tags:
    - spring
    - boot
    - demo
  database:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: 123456
    max-connections: 20
  redis:
    host: localhost
    port: 6379
    timeout: 3000

来源:https://app-a87ujc988w01.appmiaoda.com/

相关文章
|
5天前
|
人工智能 JSON 机器人
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
本文带你零成本玩转OpenClaw:学生认证白嫖6个月阿里云服务器,手把手配置飞书机器人、接入免费/高性价比AI模型(NVIDIA/通义),并打造微信公众号“全自动分身”——实时抓热榜、AI选题拆解、一键发布草稿,5分钟完成热点→文章全流程!
10731 63
让龙虾成为你的“公众号分身” | 阿里云服务器玩Openclaw
|
5天前
|
人工智能 IDE API
2026年国内 Codex 安装教程和使用教程:GPT-5.4 完整指南
Codex已进化为AI编程智能体,不仅能补全代码,更能理解项目、自动重构、执行任务。本文详解国内安装、GPT-5.4接入、cc-switch中转配置及实战开发流程,助你从零掌握“描述需求→AI实现”的新一代工程范式。(239字)
3112 126
|
1天前
|
人工智能 自然语言处理 供应链
【最新】阿里云ClawHub Skill扫描:3万个AI Agent技能中的安全度量
阿里云扫描3万+AI Skill,发现AI检测引擎可识别80%+威胁,远高于传统引擎。
1199 1
|
11天前
|
人工智能 JavaScript API
解放双手!OpenClaw Agent Browser全攻略(阿里云+本地部署+免费API+网页自动化场景落地)
“让AI聊聊天、写代码不难,难的是让它自己打开网页、填表单、查数据”——2026年,无数OpenClaw用户被这个痛点困扰。参考文章直击核心:当AI只能“纸上谈兵”,无法实际操控浏览器,就永远成不了真正的“数字员工”。而Agent Browser技能的出现,彻底打破了这一壁垒——它给OpenClaw装上“上网的手和眼睛”,让AI能像真人一样打开网页、点击按钮、填写表单、提取数据,24小时不间断完成网页自动化任务。
2563 6
|
25天前
|
人工智能 JavaScript Ubuntu
5分钟上手龙虾AI!OpenClaw部署(阿里云+本地)+ 免费多模型配置保姆级教程(MiniMax、Claude、阿里云百炼)
OpenClaw(昵称“龙虾AI”)作为2026年热门的开源个人AI助手,由PSPDFKit创始人Peter Steinberger开发,核心优势在于“真正执行任务”——不仅能聊天互动,还能自动处理邮件、管理日程、订机票、写代码等,且所有数据本地处理,隐私完全可控。它支持接入MiniMax、Claude、GPT等多类大模型,兼容微信、Telegram、飞书等主流聊天工具,搭配100+可扩展技能,成为兼顾实用性与隐私性的AI工具首选。
24388 122