Spring Boot常见YML配置、配置类和工具类代码参考
约 106 个字 453 行代码 预计阅读时间 6 分钟
Spring Boot 3.x版本示例Pom文件
| XML |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 | <?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.13</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 下面替换为实际的项目内容 -->
<!-- <groupId>org.epsda</groupId>
<artifactId>pets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>pets</name>
<description>pets</description> -->
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<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>
|
Spring Boot/SpringCloud YML常见配置项参考
| YAML |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 | spring:
application:
name: pets
servlet:
multipart:
max-file-size: 100MB # 单文件最大
max-request-size: 200MB # 总大小
datasource:
url: jdbc:mysql://localhost:3306/db_pet_service_store?characterEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
elasticsearch:
uris: http://localhost:9200
rabbitmq:
addresses: amqp://admin:admin@127.0.0.1:5672/pets
mail:
host: smtp.qq.com
username: 1848312235@qq.com
password: xxx
port: 465
properties:
mail.smtp.ssl.enable: true
personal: "宠物商城与社区系统"
ai:
openai:
api-key: xxx
base-url: https://api.deepseek.com
chat:
options:
model: deepseek-chat
temperature: 0.7
data:
redis:
host: 127.0.0.1
port: 6379
password: 037477..
database: 0
timeout: 5000ms
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 2
max-wait: 1000ms
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/**Mapper.xml
springdoc:
api-docs:
path: /v3/api-docs # 更改 OpenAPI JSON/YAML 描述文件的路径,默认是 /v3/api-docs
swagger-ui:
path: /swagger-ui.html # 更改 Swagger UI 页面的访问路径,默认是 /swagger-ui.html
packages-to-scan: org.epsda.pets.controller # 指定要扫描的包名列表(逗号分隔),只生成这些包下的接口文档
paths-to-match: /** # 指定要匹配的请求路径模式(Ant 风格),仅对符合该规则的接口生成文档
# 以下是knife4j的增强配置
knife4j:
enable: true
production: false # 不用于生产环境
setting:
language: zh_cn # 文档语言为中文
# 自定义跨域地址配置
app:
cors:
allowed-origins: http://localhost:5173,http://127.0.0.1:9999,http://localhost:3006
baidu: # 百度地图API
map:
ak: xxx
base-url: https://api.map.baidu.com/
aliyun: # 阿里云OSS
oss:
endpoint: oss-cn-hangzhou.aliyuncs.com
access-key-id: xxx
access-key-secret: xxx
bucket-name: pet-store-bucket
captcha:
width: 100
height: 40
session:
key-name: captcha-key
date-name: captcha-date
google:
oauth2:
client-id: xxx
client-secret: xxx
redirect-uri: http://ip:port/auth/google/callback
proxy: # 如果服务器开了代理就需要使用
host: 127.0.0.1
port: 7897
|
Spring Boot统一返回结果包装
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 | public record Constants() {
public static final Integer NORMAL = 0;
public static final Integer SERVER_ERROR = 1;
public static final Integer SYSTEM_ERROR = 2;
public static final Integer RESOURCE_NOT_FOUND = 3;
public static final String SERVER_ERROR_MESSAGE = "服务器异常";
public static final String SYSTEM_ERROR_MESSAGE = "图书管理系统异常";
public static final String RESOURCE_NOT_FOUND_MESSAGE = "资源不存在";
}
@Data
@AllArgsConstructor
public class ResultWrapper<T> {
private Integer code;
private String errMsg;
private T data;
// 正常情况
public static <T> ResultWrapper<T> normal(T data) {
return new ResultWrapper<>(Constants.NORMAL, "", data);
}
// 错误情况
public static <T> ResultWrapper<T> fail(T data) {
return new ResultWrapper<>(Constants.SERVER_ERROR, "", data);
}
public static <T> ResultWrapper<T> fail(Integer code, String errMsg) {
return new ResultWrapper<>(Constants.SERVER_ERROR, errMsg, null);
}
public static <T> ResultWrapper<T> fail(String errMsg, T data) {
return new ResultWrapper<>(Constants.SERVER_ERROR, errMsg, data);
}
}
|
Spring Boot统一异常
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 | @Slf4j
@ControllerAdvice
@ResponseBody // 防止出现持续返回视图导致的死循环情况
// 也可以使用下面的注解 @RestControllerAdvice 代替 @ControllerAdvice 和 @ResponseBody
public class ExceptionAdvice {
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(Exception.class)
public ResultWrapper allExceptionHandler(Exception e) {
// 详细日志只在后端记录
log.error("系统异常: ", e);
// 参数校验异常,返回具体校验信息
if (e instanceof MethodArgumentNotValidException validException) {
String errMsg = validException.getBindingResult().getFieldError().getDefaultMessage();
return ResultWrapper.fail(Constants.SERVER_ERROR, errMsg);
}
// 其他异常返回通用提示,不暴露技术细节
return ResultWrapper.fail(Constants.SERVER_ERROR, Constants.SERVER_ERROR_MESSAGE);
}
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(MusicException.class)
public ResultWrapper musicExceptionHandler(MusicException e) {
// 业务异常记录日志
log.warn("业务异常: {}", e.getMessage());
// 业务异常可以返回具体提示(因为是我们自己定义的友好提示)
return ResultWrapper.fail(Constants.SYSTEM_ERROR, e.getMessage());
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler(NoResourceFoundException.class)
public ResultWrapper noResourceFoundException(NoResourceFoundException e) {
log.warn("资源不存在: {}", e.getResourcePath());
return ResultWrapper.fail(Constants.RESOURCE_NOT_FOUND, Constants.RESOURCE_NOT_FOUND_MESSAGE);
}
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(IllegalStateException.class)
public ResultWrapper illegalStateExceptionHandler(IllegalStateException e) {
log.warn("状态异常: {}", e.getMessage());
// 状态异常通常是业务逻辑问题,返回具体提示
return ResultWrapper.fail(Constants.SYSTEM_ERROR, e.getMessage());
}
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(RuntimeException.class)
public ResultWrapper runtimeExceptionHandler(RuntimeException e) {
log.error("运行时异常: ", e);
// 检查是否是初始化相关的异常,返回友好提示
String message = e.getMessage();
if (message != null && message.contains("连接")) {
return ResultWrapper.fail(Constants.SYSTEM_ERROR, "连接失败,请检查网络或重试");
}
if (message != null && message.contains("Cookie")) {
return ResultWrapper.fail(Constants.SYSTEM_ERROR, "Cookie 无效或已过期,请重新输入");
}
// 其他运行时异常返回通用提示
return ResultWrapper.fail(Constants.SERVER_ERROR, Constants.SERVER_ERROR_MESSAGE);
}
}
|
Spring Boot统一跨域解决
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | @Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${app.cors.allowed-origins}") // 参考通用配置文件
private String allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = allowedOrigins.split(",");
registry.addMapping("/**")
.allowedOrigins(origins)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
|
自定义异常参考
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | @Data
@EqualsAndHashCode(callSuper = true)
public class BookManagerException extends RuntimeException{
public Integer code;
public String message;
public BookManagerException() {
}
public BookManagerException(Integer code) {
this.code = code;
}
public BookManagerException(String message) {
this.message = message;
}
public BookManagerException(Integer code, String message) {
this.code = code;
this.message = message;
}
}
|
JSON工具类(基于FastJson)
FastJson依赖:
| XML |
|---|
| <dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.59</version>
</dependency>
|
工具类:
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 | @Slf4j
public class JsonUtil {
// 对象转Json字符串
public static String toJson(Object o) {
try {
return o == null ? null : JSON.toJSONString(o);
} catch (Exception e) {
log.error("对象转JSON字符串出现异常,e:{}", e.getMessage());
return null;
}
}
// Json字符串转对象
public static <T> T toObject(String json, Class<T> cls) {
try {
if (cls == null || !StringUtils.hasLength(json)) {
return null;
}
return JSON.parseObject(json, cls);
} catch (Exception e) {
log.error("JSON字符串转对象出现异常,e:{}", e.getMessage());
return null;
}
}
}
|
Jwt工具类
引入依赖:
| XML |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
|
邮件发送工具类
| Java |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | @Component
public class MailUtil {
private static final Logger log = LoggerFactory.getLogger(MailUtil.class);
private final JavaMailSender javaMailSender;
private final MailProperties mailProperties;
public MailUtil(JavaMailSender javaMailSender, MailProperties mailProperties) {
this.javaMailSender = javaMailSender;
this.mailProperties = mailProperties;
}
public boolean sendMail(String to, String subject, String html) throws Exception {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
mimeMessageHelper.setFrom(mailProperties.getUsername(), mailProperties.getProperties().get("personal"));
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(html, true);
try {
javaMailSender.send(mimeMessage);
return true;
} catch (MailException e) {
log.error("邮件发送失败, to={}, subject={}", to, subject, e);
return false;
}
}
}
|