SpringBoot常见YML配置、配置类和工具类代码参考
约 100 个字 426 行代码 预计阅读时间 6 分钟
SpringBoot 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.2.4</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>
|
SpringBoot/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 | spring:
application:
name: book-manager
servlet:
multipart:
max-file-size: 5MB # 单个文件最大5MB
max-request-size: 10MB # 整个请求最大10MB
datasource:
url: jdbc:mysql://localhost:3306/book_manager?characterEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
rabbitmq:
addresses: amqp://admin:admin@ip:port/blog
listener:
simple:
acknowledge-mode: manual # 手动确认
data:
redis:
host: 47.113.217.80
port: 6376
timeout: 60s
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 5s
mail:
host: smtp.qq.com
username: 1848312235@qq.com
password: xxxx
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
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# ⽇志配置
logging:
pattern:
dateformat: HH:mm:ss
level:
root: info # 默认⽇志级别
com.epsda.book.controller: debug # 指定包的⽇志级别
# 自定义Hutools验证码配置
captcha:
width: 100
height: 40
session:
key-name: captcha-key
date-name: captcha-date
# 自定义头像上传地址
avatar:
upload:
path: E:\BookManager\backend\images
# 自定义管理员名称
admin:
admin-name: book_admin_001
# 自定义跨域地址配置
app:
cors:
allowed-origins: http://localhost:9999,http://127.0.0.1:9999
|
SpringBoot统一返回结果包装
| 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);
}
}
|
SpringBoot统一异常
| 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 | @Slf4j
@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);
}
}
|
SpringBoot统一跨域解决
| 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 | @Component
public class MailUtil {
private final JavaMailSender javaMailSender;
private final MailProperties mailProperties;
public MailUtil(JavaMailSender javaMailSender, MailProperties mailProperties) {
this.javaMailSender = javaMailSender;
this.mailProperties = mailProperties;
}
public void 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);
javaMailSender.send(mimeMessage);
}
}
|