当前位置: 首页 > news >正文

SpringBoot框架完整学习指南

目录

1. SpringBoot简介

1.1 什么是SpringBoot

1.2 SpringBoot的优势

1.3 SpringBoot vs Spring

1.4 SpringBoot核心特性

2. 快速入门

2.1 开发环境准备

2.2 创建SpringBoot项目

方式一:使用Spring Initializr(推荐)

方式二:使用IDE创建

方式三:使用Maven手动创建

2.3 第一个SpringBoot应用

2.4 运行应用

方式一:IDE中运行

方式二:Maven命令运行

方式三:打包后运行

2.5 @SpringBootApplication注解详解

2.6 配置文件

3. 自动配置原理

3.1 自动配置概述

3.2 @EnableAutoConfiguration原理

3.3 spring.factories文件

3.4 条件注解

3.5 WebMvc自动配置分析

3.6 自定义自动配置

3.7 排除自动配置

3.8 查看自动配置报告

4. 配置文件详解

4.1 配置文件类型

4.2 配置文件优先级

4.3 多环境配置

4.4 配置文件位置

4.5 YAML语法详解

4.6 自定义配置属性

4.7 松散绑定

4.8 配置随机值

4.9 配置文件加密

4.10 条件配置

5. 依赖管理

5.1 起步依赖概述

5.2 SpringBoot父项目

5.3 常用起步依赖

5.4 版本管理

5.5 自定义起步依赖

5.6 依赖排除

5.7 Gradle依赖管理

5.8 依赖分析工具

6. Web开发

6.1 SpringBoot Web开发概述

6.2 Web开发环境搭建

6.3 控制器开发

6.4 静态资源处理

6.5 模板引擎

6.6 内嵌服务器配置

6.7 错误处理

6.8 拦截器配置

6.9 过滤器配置

6.10 CORS跨域配置

7. 数据访问

7.1 数据访问概述

7.2 数据源配置

7.3 JPA集成

7.4 MyBatis集成

7.5 Redis集成

7.6 MongoDB集成

7.7 事务管理

8. 安全管理

8.1 Spring Security集成

8.2 基本安全配置

8.3 用户认证

8.4 JWT令牌认证

8.5 认证控制器

8.6 方法级安全

8.7 自定义安全注解

8.8 OAuth2集成

9. 缓存机制

9.1 缓存概述

9.2 启用缓存

9.3 缓存注解

9.4 Redis缓存配置

9.5 EhCache配置

9.6 Caffeine缓存配置

9.7 自定义缓存Key生成器

9.8 缓存条件表达式

9.9 缓存监控和管理

10. 消息队列

10.1 消息队列概述

10.2 RabbitMQ集成

10.3 Kafka集成

10.4 消息事务

11. 测试框架

11.1 测试概述

11.2 测试依赖

11.3 单元测试

11.4 集成测试

11.5 Web层测试

11.6 数据层测试

11.7 消息队列测试

11.8 缓存测试

11.9 测试配置

12. 监控和管理

12.1 Actuator概述

12.2 Actuator端点配置

12.3 健康检查

12.4 应用信息

12.5 自定义指标

12.6 日志管理

12.7 审计功能

12.8 安全配置

12.9 监控集成

13. 部署方式

13.1 部署概述

13.2 JAR包部署

13.3 WAR包部署

13.4 Docker部署

13.5 Kubernetes部署

13.6 云平台部署

13.7 原生镜像部署

13.8 性能优化

14. 微服务开发

14.1 微服务概述

14.2 Spring Cloud集成

14.3 服务注册与发现

14.4 服务间通信

14.5 配置中心

14.6 API网关

14.7 熔断器

14.8 分布式追踪

14.9 消息驱动微服务

15. 最佳实践

15.1 项目结构

15.2 配置管理

15.3 异常处理

15.4 日志管理

15.5 安全最佳实践

15.6 性能优化

15.7 API设计

15.8 测试策略

15.9 监控和告警

15.10 部署和运维

总结


1. SpringBoot简介

1.1 什么是SpringBoot

SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。SpringBoot基于"约定优于配置"的理念,极大地简化了Spring应用的开发。

简单理解:

  • 传统Spring项目就像手工装配电脑,需要一个个配置各种组件
  • SpringBoot就像品牌组装机,开箱即用,自动配置好了大部分组件

1.2 SpringBoot的优势

1. 快速创建项目

  • 提供了大量的启动器(Starter),一键引入相关依赖
  • 内嵌服务器,无需部署WAR包
  • 提供项目模板和脚手架

2. 自动配置

  • 根据类路径自动配置Spring和第三方库
  • 提供默认配置,开箱即用
  • 可以通过配置文件轻松修改默认配置

3. 独立运行

  • 内嵌Tomcat、Jetty等服务器
  • 打包成JAR文件,java -jar即可运行
  • 无需外部容器

4. 监控功能

  • 提供生产级别的应用监控和管理功能
  • 健康检查、指标收集、配置信息等

1.3 SpringBoot vs Spring

对比项SpringSpringBoot
配置方式大量XML配置或Java配置约定优于配置,自动配置
项目搭建手动搭建,配置繁琐快速搭建,开箱即用
依赖管理需要手动管理版本兼容性统一版本管理
服务器需要外部服务器内嵌服务器
部署方式WAR包部署到服务器JAR包独立运行

1.4 SpringBoot核心特性

1. 起步依赖(Starter Dependencies)

<!-- 一个starter包含了该功能所需的所有依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 自动配置(Auto Configuration)

// SpringBoot会自动扫描类路径,自动配置相应的Bean
@SpringBootApplication  // 这个注解包含了自动配置功能
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}

3. 命令行界面(Spring Boot CLI)

# 可以直接运行Groovy脚本
spring run app.groovy

4. Actuator监控

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2. 快速入门

2.1 开发环境准备

必需工具:

  • JDK 8+:SpringBoot 2.x要求JDK 8以上
  • Maven 3.6+ 或 Gradle 6+:构建工具
  • IDE:推荐IntelliJ IDEA或Eclipse STS

推荐工具:

  • Spring Tool Suite (STS):专门为Spring开发的IDE
  • Spring Boot CLI:命令行工具
  • Postman:API测试工具

2.2 创建SpringBoot项目

方式一:使用Spring Initializr(推荐)

在线创建: https://start.spring.io/

  1. 选择项目类型:Maven Project
  2. 选择语言:Java
  3. 选择SpringBoot版本:2.7.0
  4. 填写项目信息:
    • Group:com.example
    • Artifact:demo
    • Name:demo
    • Package name:com.example.demo
    • Packaging:Jar
    • Java版本:8
  5. 添加依赖:Spring Web
  6. 点击Generate下载项目
方式二:使用IDE创建

IntelliJ IDEA:

  1. File → New → Project
  2. 选择Spring Initializr
  3. 填写项目信息
  4. 选择依赖
  5. 创建项目
方式三:使用Maven手动创建

项目结构:

demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/example/demo/
│   │   │       └── DemoApplication.java
│   │   └── resources/
│   │       ├── static/        # 静态资源
│   │       ├── templates/     # 模板文件
│   │       └── application.properties  # 配置文件
│   └── test/
│       └── java/
│           └── com/example/demo/
│               └── DemoApplicationTests.java
├── target/
├── pom.xml
└── README.md

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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- 继承SpringBoot父项目 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.0</version><relativePath/></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>8</java.version></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></dependencies><build><plugins><!-- SpringBoot Maven插件 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

2.3 第一个SpringBoot应用

主启动类:DemoApplication.java

package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication  // SpringBoot核心注解
public class DemoApplication {public static void main(String[] args) {// 启动SpringBoot应用SpringApplication.run(DemoApplication.class, args);}
}

创建控制器:HelloController.java

package com.example.demo.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController  // 相当于 @Controller + @ResponseBody
public class HelloController {@GetMapping("/hello")public String hello(@RequestParam(defaultValue = "World") String name) {return String.format("Hello, %s!", name);}@GetMapping("/")public String index() {return "Welcome to Spring Boot!";}
}

2.4 运行应用

方式一:IDE中运行

直接在IDE中运行DemoApplication类的main方法。

方式二:Maven命令运行
# 在项目根目录执行
mvn spring-boot:run
方式三:打包后运行
# 打包
mvn clean package# 运行JAR包
java -jar target/demo-0.0.1-SNAPSHOT.jar

访问测试:

  • 打开浏览器访问:http://localhost:8080
  • 访问:http://localhost:8080/hello?name=SpringBoot

2.5 @SpringBootApplication注解详解

@SpringBootApplication是一个组合注解,包含了三个重要注解:

@SpringBootApplication
// 等价于以下三个注解的组合:
@SpringBootConfiguration  // 标识这是一个配置类
@EnableAutoConfiguration  // 启用自动配置
@ComponentScan            // 启用组件扫描
public class DemoApplication {// ...
}

详细解释:

1. @SpringBootConfiguration

// 表示这是一个配置类,相当于@Configuration
@SpringBootConfiguration
public class DemoApplication {@Bean  // 可以在这里定义Beanpublic String appName() {return "My SpringBoot App";}
}

2. @EnableAutoConfiguration

// 启用SpringBoot的自动配置机制
// 会根据类路径自动配置Bean
@EnableAutoConfiguration
public class DemoApplication {// SpringBoot会自动配置:// - DispatcherServlet(如果有spring-webmvc)// - DataSource(如果有数据库依赖)// - JPA(如果有spring-data-jpa)// 等等...
}

3. @ComponentScan

// 启用组件扫描,默认扫描当前包及子包
@ComponentScan(basePackages = "com.example.demo")
public class DemoApplication {// 会自动扫描并注册:// - @Component// - @Service// - @Repository// - @Controller// 等注解标注的类
}

2.6 配置文件

application.properties(默认配置文件)

# 服务器配置
server.port=8080
server.servlet.context-path=/api# 应用配置
spring.application.name=demo# 日志配置
logging.level.com.example.demo=DEBUG
logging.file.name=app.log# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=123456

application.yml(YAML格式,推荐)

server:port: 8080servlet:context-path: /apispring:application:name: demodatasource:url: jdbc:mysql://localhost:3306/testdbusername: rootpassword: 123456logging:level:com.example.demo: DEBUGfile:name: app.log

3. 自动配置原理

3.1 自动配置概述

SpringBoot的自动配置是其核心特性之一,它能够根据类路径中的jar包、类、属性等信息自动配置Spring容器中的Bean。

自动配置的工作原理:

启动应用 → 扫描类路径 → 判断条件 → 自动配置Bean → 启动完成

3.2 @EnableAutoConfiguration原理

@EnableAutoConfiguration
// 实际上导入了AutoConfigurationImportSelector
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {// ...
}

AutoConfigurationImportSelector的工作流程:

  1. 扫描所有jar包下的META-INF/spring.factories文件
  2. 加载所有的自动配置类
  3. 根据条件注解判断是否需要配置
  4. 实例化符合条件的配置类

3.3 spring.factories文件

spring-boot-autoconfigure.jar中的spring.factories:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
# ... 还有很多自动配置类

3.4 条件注解

SpringBoot使用大量的条件注解来控制自动配置:

常用条件注解:

@ConditionalOnClass(DispatcherServlet.class)        // 类存在时
@ConditionalOnMissingClass("com.example.SomeClass") // 类不存在时
@ConditionalOnBean(DataSource.class)                // Bean存在时
@ConditionalOnMissingBean(DataSource.class)         // Bean不存在时
@ConditionalOnProperty(name = "spring.aop.auto", havingValue = "true") // 属性满足条件时
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) // Web应用时

条件注解示例:

@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {@Bean@Primary@ConditionalOnMissingBean(JdbcOperations.class)public JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties properties) {JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);JdbcProperties.Template template = properties.getTemplate();jdbcTemplate.setFetchSize(template.getFetchSize());jdbcTemplate.setMaxRows(template.getMaxRows());return jdbcTemplate;}
}

3.5 WebMvc自动配置分析

WebMvcAutoConfiguration类(简化版本):

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class })
public class WebMvcAutoConfiguration {// 配置视图解析器@Bean@ConditionalOnMissingBeanpublic InternalResourceViewResolver defaultViewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix(this.mvcProperties.getView().getPrefix());resolver.setSuffix(this.mvcProperties.getView().getSuffix());return resolver;}// 配置静态资源处理@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {return;}Duration cachePeriod = this.resourceProperties.getCache().getPeriod();CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();if (!registry.hasMappingForPattern("/webjars/**")) {customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));}String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));}}
}

3.6 自定义自动配置

1. 创建自动配置类

@Configuration
@ConditionalOnClass(MyService.class)
@ConditionalOnProperty(name = "myservice.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(MyServiceProperties.class)
public class MyServiceAutoConfiguration {@Autowiredprivate MyServiceProperties properties;@Bean@ConditionalOnMissingBeanpublic MyService myService() {return new MyService(properties.getName(), properties.getTimeout());}
}

2. 创建配置属性类

@ConfigurationProperties(prefix = "myservice")
public class MyServiceProperties {private String name = "default";private int timeout = 30;// getter和setter...
}

3. 创建服务类

public class MyService {private String name;private int timeout;public MyService(String name, int timeout) {this.name = name;this.timeout = timeout;}public void doSomething() {System.out.println("MyService: " + name + ", timeout: " + timeout);}
}

4. 创建spring.factories文件

src/main/resources/META-INF/spring.factories中添加:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.autoconfigure.MyServiceAutoConfiguration

5. 使用自动配置

# application.yml
myservice:enabled: truename: custom-servicetimeout: 60
@RestController
public class TestController {@Autowiredprivate MyService myService;  // 自动注入@GetMapping("/test")public String test() {myService.doSomething();return "success";}
}

3.7 排除自动配置

方式一:使用exclude属性

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

方式二:使用配置文件

spring:autoconfigure:exclude:- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration- org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

3.8 查看自动配置报告

启用自动配置报告:

# application.yml
logging:level:org.springframework.boot.autoconfigure: DEBUG

或者在启动时添加参数:

java -jar app.jar --debug

自动配置报告示例:

=========================
AUTO-CONFIGURATION REPORT
=========================Positive matches:  # 匹配的自动配置
-----------------DispatcherServletAutoConfiguration matched:- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'- @ConditionalOnWebApplication (required) found 'session' scopeNegative matches:  # 不匹配的自动配置
-----------------ActiveMQAutoConfiguration:Did not match:- @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory'Exclusions:  # 被排除的自动配置
-----------NoneUnconditional classes:  # 无条件的自动配置
----------------------None

4. 配置文件详解

4.1 配置文件类型

SpringBoot支持多种配置文件格式:

1. application.properties(Java属性文件)

server.port=8080
spring.application.name=my-app

2. application.yml/application.yaml(YAML格式,推荐)

server:port: 8080
spring:application:name: my-app

3. application.json(JSON格式)

{"server": {"port": 8080},"spring": {"application": {"name": "my-app"}}
}

4.2 配置文件优先级

SpringBoot会按照以下顺序查找配置文件(优先级从高到低):

  1. 命令行参数
java -jar app.jar --server.port=8081
  1. SPRING_APPLICATION_JSON环境变量
export SPRING_APPLICATION_JSON='{"server":{"port":8081}}'
  1. System.getProperties()系统属性
System.setProperty("server.port", "8081");
  1. 操作系统环境变量
export SERVER_PORT=8081
  1. jar包外部的application-{profile}.properties/yml
  2. jar包内部的application-{profile}.properties/yml
  3. jar包外部的application.properties/yml
  4. jar包内部的application.properties/yml

4.3 多环境配置

profile文件命名规则:

application-{profile}.properties
application-{profile}.yml

开发环境配置:application-dev.yml

server:port: 8080
spring:datasource:url: jdbc:mysql://localhost:3306/dev_dbusername: dev_userpassword: dev_pass
logging:level:com.example: DEBUG

测试环境配置:application-test.yml

server:port: 8081
spring:datasource:url: jdbc:mysql://test-server:3306/test_dbusername: test_userpassword: test_pass
logging:level:root: INFO

生产环境配置:application-prod.yml

server:port: 80
spring:datasource:url: jdbc:mysql://prod-server:3306/prod_dbusername: prod_userpassword: ${DB_PASSWORD}  # 从环境变量获取
logging:level:root: WARNfile:name: /var/log/app.log

激活profile的方式:

1. 配置文件方式

# application.yml
spring:profiles:active: dev  # 激活dev环境

2. 命令行方式

java -jar app.jar --spring.profiles.active=prod

3. 环境变量方式

export SPRING_PROFILES_ACTIVE=prod

4. 程序中设置

@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication app = new SpringApplication(Application.class);app.setAdditionalProfiles("dev");app.run(args);}
}

4.4 配置文件位置

SpringBoot会按照以下顺序查找配置文件:

  1. file:./config/(项目根目录下的config文件夹)
  2. file:./(项目根目录)
  3. classpath:/config/(classpath下的config包)
  4. classpath:/(classpath根目录)

自定义配置文件位置:

java -jar app.jar --spring.config.location=classpath:/custom/,file:./custom/

4.5 YAML语法详解

基本语法:

# 键值对
key: value# 对象
person:name: Johnage: 30# 数组
fruits:- apple- banana- orange# 行内写法
person: {name: John, age: 30}
fruits: [apple, banana, orange]# 多行字符串
description: |这是一个多行字符串第二行第三行# 折叠字符串
summary: >这是一个很长的字符串会被折叠成一行# 引用
defaults: &defaultsadapter: postgreshost: localhostdevelopment:database: myapp_development<<: *defaults  # 引用defaults# 环境变量
database:password: ${DB_PASSWORD:defaultpass}  # 从环境变量获取,默认值为defaultpass

4.6 自定义配置属性

1. 使用@Value注解

@Component
public class MyComponent {@Value("${app.name}")private String appName;@Value("${app.version:1.0}")  // 默认值private String appVersion;@Value("${app.timeout:30}")private int timeout;// SpEL表达式@Value("#{${app.config}}")private Map<String, String> config;
}

2. 使用@ConfigurationProperties(推荐)

配置文件:

app:name: MyAppversion: 1.0email: admin@example.comservers:- name: server1ip: 192.168.1.1port: 8080- name: server2ip: 192.168.1.2port: 8081database:url: jdbc:mysql://localhost:3306/mydbusername: rootpassword: 123456

配置属性类:

@Component
@ConfigurationProperties(prefix = "app")
@Validated  // 启用验证
public class AppProperties {@NotBlankprivate String name;private String version;@Emailprivate String email;@Validprivate List<Server> servers = new ArrayList<>();@Validprivate Database database = new Database();// 内部类public static class Server {@NotBlankprivate String name;@NotBlankprivate String ip;@Min(1)@Max(65535)private int port;// getter和setter...}public static class Database {@NotBlankprivate String url;@NotBlankprivate String username;@NotBlankprivate String password;// getter和setter...}// getter和setter...
}

使用配置属性:

@RestController
public class ConfigController {@Autowiredprivate AppProperties appProperties;@GetMapping("/config")public AppProperties getConfig() {return appProperties;}@GetMapping("/servers")public List<AppProperties.Server> getServers() {return appProperties.getServers();}
}

4.7 松散绑定

SpringBoot支持松散绑定,以下命名方式都能正确绑定:

# 配置文件中的不同写法都能绑定到firstName属性
person:first-name: John    # 推荐:短横线分隔firstName: John     # 驼峰命名first_name: John    # 下划线分隔FIRST_NAME: John    # 大写下划线(环境变量风格)

环境变量绑定:

# 环境变量
export PERSON_FIRST_NAME=John
export PERSON_AGE=30# 系统属性
-Dperson.first-name=John
-Dperson.age=30

4.8 配置随机值

SpringBoot提供了RandomValuePropertySource来生成随机值:

# 随机字符串
my:secret: ${random.value}number: ${random.int}bignumber: ${random.long}uuid: ${random.uuid}# 指定范围的随机数number-less-than-ten: ${random.int(10)}number-in-range: ${random.int[1024,65536]}

4.9 配置文件加密

使用jasypt进行配置加密:

1. 添加依赖

<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.4</version>
</dependency>

2. 配置加密密钥

jasypt:encryptor:password: mySecretKeyalgorithm: PBEWithMD5AndDES

3. 加密敏感信息

// 生成加密字符串的工具类
public class EncryptUtil {public static void main(String[] args) {BasicTextEncryptor textEncryptor = new BasicTextEncryptor();textEncryptor.setPassword("mySecretKey");String myEncryptedText = textEncryptor.encrypt("root");System.out.println(myEncryptedText);}
}

4. 在配置文件中使用加密值

spring:datasource:username: ENC(加密后的字符串)password: ENC(加密后的字符串)

4.10 条件配置

使用@ConditionalOnProperty

@Configuration
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureConfiguration {@Beanpublic FeatureService featureService() {return new FeatureService();}
}

使用@Profile

@Configuration
@Profile("dev")
public class DevConfiguration {@Beanpublic DataSource dataSource() {return new EmbeddedDatabaseBuilder().build();}
}@Configuration
@Profile("prod")
public class ProdConfiguration {@Beanpublic DataSource dataSource() {// 生产环境数据源配置return new HikariDataSource();}
}

在配置文件中使用profile

# application.yml
spring:profiles:active: dev---
# dev profile
spring:profiles: devdatasource:url: jdbc:h2:mem:testdb---
# prod profile
spring:profiles: proddatasource:url: jdbc:mysql://prod-server:3306/db

5. 依赖管理

5.1 起步依赖概述

SpringBoot的起步依赖(Starter)是一组预配置的依赖描述符,通过一个起步依赖可以获取所需的所有Spring和相关技术的依赖。

起步依赖的优势:

  • 简化依赖管理:一个starter包含相关的所有依赖
  • 版本兼容性:starter确保依赖版本的兼容性
  • 减少配置:提供默认配置,开箱即用
  • 自动配置:配合自动配置机制,无需手动配置

5.2 SpringBoot父项目

继承spring-boot-starter-parent:

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

spring-boot-starter-parent提供了:

  • 默认的Java版本
  • 默认的编码格式(UTF-8)
  • 依赖版本管理
  • 默认的插件配置
  • 资源过滤配置

5.3 常用起步依赖

Web开发相关:

<!-- Web启动器:包含SpringMVC、Tomcat、Jackson等 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- WebFlux响应式Web -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency><!-- Thymeleaf模板引擎 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency><!-- WebSocket -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

数据访问相关:

<!-- JDBC -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency><!-- JPA -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency><!-- MongoDB -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency><!-- Redis -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!-- MyBatis -->
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version>
</dependency>

消息队列相关:

<!-- AMQP (RabbitMQ) -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency><!-- Apache Kafka -->
<dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId>
</dependency>

安全相关:

<!-- Spring Security -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency><!-- OAuth2 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

测试相关:

<!-- 测试启动器 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>

监控相关:

<!-- Actuator监控 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

5.4 版本管理

SpringBoot版本管理原理:

<!-- spring-boot-dependencies中定义了大量依赖的版本 -->
<properties><spring-framework.version>5.3.21</spring-framework.version><spring-data-bom.version>2021.2.0</spring-data-bom.version><spring-security.version>5.7.1</spring-security.version><jackson-bom.version>2.13.3</jackson-bom.version><junit-jupiter.version>5.8.2</junit-jupiter.version><!-- 还有很多... -->
</properties>

覆盖默认版本:

<properties><mysql.version>8.0.29</mysql.version><junit.version>4.13.2</junit.version>
</properties>

不继承parent的情况:

<!-- 如果不能继承parent,可以使用import scope -->
<dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.7.0</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>

5.5 自定义起步依赖

创建自定义starter的步骤:

1. 创建autoconfigure模块

项目结构:

my-spring-boot-starter/
├── my-spring-boot-autoconfigure/
│   ├── src/main/java/
│   │   └── com/example/autoconfigure/
│   │       ├── MyServiceAutoConfiguration.java
│   │       ├── MyServiceProperties.java
│   │       └── MyService.java
│   ├── src/main/resources/
│   │   └── META-INF/
│   │       └── spring.factories
│   └── pom.xml
└── my-spring-boot-starter/└── pom.xml

autoconfigure模块的pom.xml:

<artifactId>my-spring-boot-autoconfigure</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>
</dependencies>

自动配置类:

@Configuration
@ConditionalOnClass(MyService.class)
@EnableConfigurationProperties(MyServiceProperties.class)
public class MyServiceAutoConfiguration {@Autowiredprivate MyServiceProperties properties;@Bean@ConditionalOnMissingBeanpublic MyService myService() {MyService service = new MyService();service.setPrefix(properties.getPrefix());service.setSuffix(properties.getSuffix());return service;}
}

配置属性类:

@ConfigurationProperties(prefix = "myservice")
public class MyServiceProperties {private String prefix = "Hello";private String suffix = "!";// getter和setter...
}

服务类:

public class MyService {private String prefix;private String suffix;public String format(String message) {return prefix + " " + message + " " + suffix;}// getter和setter...
}

spring.factories文件:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.autoconfigure.MyServiceAutoConfiguration

2. 创建starter模块

starter模块的pom.xml:

<artifactId>my-spring-boot-starter</artifactId><dependencies><!-- 引入autoconfigure模块 --><dependency><groupId>com.example</groupId><artifactId>my-spring-boot-autoconfigure</artifactId><version>${project.version}</version></dependency><!-- 引入其他需要的依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency>
</dependencies>

3. 使用自定义starter

在其他项目中使用:

<dependency><groupId>com.example</groupId><artifactId>my-spring-boot-starter</artifactId><version>1.0.0</version>
</dependency>

配置文件:

myservice:prefix: Hisuffix: !!!

使用服务:

@RestController
public class TestController {@Autowiredprivate MyService myService;@GetMapping("/test")public String test() {return myService.format("SpringBoot");  // 输出: Hi SpringBoot !!!}
}

5.6 依赖排除

排除某个依赖:

<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><!-- 使用其他Web服务器 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

排除传递依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId><exclusions><exclusion><groupId>com.h2database</groupId><artifactId>h2</artifactId></exclusion></exclusions>
</dependency>

5.7 Gradle依赖管理

build.gradle配置:

plugins {id 'org.springframework.boot' version '2.7.0'id 'io.spring.dependency-management' version '1.0.11.RELEASE'id 'java'
}group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'repositories {mavenCentral()
}dependencies {implementation 'org.springframework.boot:spring-boot-starter-web'implementation 'org.springframework.boot:spring-boot-starter-data-jpa'runtimeOnly 'mysql:mysql-connector-java'testImplementation 'org.springframework.boot:spring-boot-starter-test'
}test {useJUnitPlatform()
}

排除依赖:

dependencies {implementation('org.springframework.boot:spring-boot-starter-web') {exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'}implementation 'org.springframework.boot:spring-boot-starter-jetty'
}

5.8 依赖分析工具

Maven依赖分析:

# 查看依赖树
mvn dependency:tree# 分析依赖冲突
mvn dependency:analyze# 查看有效POM
mvn help:effective-pom

Gradle依赖分析:

# 查看依赖树
./gradlew dependencies# 查看特定配置的依赖
./gradlew dependencies --configuration runtimeClasspath

IDE插件:

  • IntelliJ IDEA:Maven Helper插件
  • Eclipse:M2Eclipse插件

6. Web开发

6.1 SpringBoot Web开发概述

SpringBoot提供了强大的Web开发支持,包括:

  • 内嵌Web服务器(Tomcat、Jetty、Undertow)
  • 自动配置SpringMVC
  • 静态资源处理
  • 模板引擎支持
  • RESTful API开发
  • 异常处理
  • 拦截器和过滤器

6.2 Web开发环境搭建

添加Web依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

spring-boot-starter-web包含的依赖:

  • spring-boot-starter
  • spring-boot-starter-tomcat(内嵌Tomcat)
  • spring-web、spring-webmvc
  • jackson(JSON处理)

6.3 控制器开发

基本控制器:

@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.findAll();}@GetMapping("/{id}")public ResponseEntity<User> getUserById(@PathVariable Long id) {User user = userService.findById(id);if (user != null) {return ResponseEntity.ok(user);}return ResponseEntity.notFound().build();}@PostMappingpublic ResponseEntity<User> createUser(@Valid @RequestBody User user) {User savedUser = userService.save(user);URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri();return ResponseEntity.created(location).body(savedUser);}@PutMapping("/{id}")public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {user.setId(id);User updatedUser = userService.update(user);return ResponseEntity.ok(updatedUser);}@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {userService.deleteById(id);return ResponseEntity.noContent().build();}
}

传统MVC控制器:

@Controller
@RequestMapping("/users")
public class UserWebController {@Autowiredprivate UserService userService;@GetMappingpublic String listUsers(Model model) {model.addAttribute("users", userService.findAll());return "users/list";  // 返回视图名}@GetMapping("/new")public String newUserForm(Model model) {model.addAttribute("user", new User());return "users/form";}@PostMappingpublic String saveUser(@Valid User user, BindingResult result, Model model) {if (result.hasErrors()) {return "users/form";}userService.save(user);return "redirect:/users";}@GetMapping("/{id}/edit")public String editUserForm(@PathVariable Long id, Model model) {User user = userService.findById(id);model.addAttribute("user", user);return "users/form";}@PostMapping("/{id}/delete")public String deleteUser(@PathVariable Long id) {userService.deleteById(id);return "redirect:/users";}
}

6.4 静态资源处理

默认静态资源位置: SpringBoot会自动配置静态资源处理,默认位置包括:

  • /static
  • /public
  • /resources
  • /META-INF/resources

项目结构示例:

src/main/resources/
├── static/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── app.js
│   └── images/
│       └── logo.png
├── public/
│   └── favicon.ico
└── templates/└── index.html
http://www.dtcms.com/a/270393.html

相关文章:

  • [创业之路-489]:企业经营层 - 营销 - 如何将缺点转化为特点、再将特点转化为卖点
  • 钉钉企业应用开发技巧:在单聊会话中实现互动卡片功能
  • 学习日记-spring-day43-7.8
  • 基于物联网架构的温室环境温湿度传感器节点设计
  • 扣子Coze纯前端部署多Agents
  • WouoUI-Page移植
  • Java-Collections、Map
  • H3初识——入门介绍之常用中间件
  • 11款常用C++在线编译与运行平台推荐与对比
  • ffmpeg 中config 文件一些理解
  • Flutter基础(前端教程②-卡片列表)
  • study_WebView介绍
  • MYSQL进阶知识
  • 在keil中使用stlink下载程序报错Invalid ROM Table
  • Day07_C语言IO进程线程(重难点)
  • TensorFlow 和PyTorch的全方位对比和选择建议
  • Latex几种常用的花体
  • [2-02-02].第04节:环境搭建 - Linux搭建ES集群环境
  • [RPA] 影刀RPA基本知识
  • Kafka多组消费:同一Topic,不同Group ID
  • NV298NV312美光固态闪存NW639NW640
  • 基于mysqlfrm工具解析mysql数据结构文件frm表结构和数据库版本信息
  • 【Nginx】Nginx代理WebSocket
  • 扣子Coze远程连接数据库插件
  • C语言基础(1)
  • 【C++】AVL树底层思想 and 大厂面试
  • Python 的内置函数 slice
  • 为什么elementui的<el-table-column label=“名称“ prop=“name“ label不用写成:label
  • RS-232协议与RS485协议详解
  • [Backlog] 命令行界面CLI vs Web界面及服务端