Java后端本地调试实用方法总结大全
作者:廋到被风吹走
这篇文章主要介绍了Java后端本地调试实用方法总结大全的相关资料,每个部分都提供了实用的技巧和工具推荐,帮助开发者提高调试效率,文中介绍的非常详细,需要的朋友可以参考下
一、IDE 调试基础技巧
1.IDEA 断点调试(必备)
核心功能:
- 行断点:单击 gutter 设置断点
- 条件断点:右键断点设置条件表达式(如
userId != null && userId > 100) - 日志断点:不暂停程序,仅打印日志(右键 Suspend 取消勾选)
- 异常断点:Debug 窗口 → View Breakpoints → + Java Exception Breakpoints
实用技巧:
Alt + F8:Evaluate Expression 动态执行代码Ctrl + F8:快速切换行断点Ctrl + Shift + F8:管理所有断点- Drop Frame:回退到方法调用前(堆栈帧),重新执行
二、日志与监控
2.SLF4J + Logback 动态日志级别
场景:生产环境无法重启,需动态调整日志排查问题。
配置:
# application.yml
logging:
level:
root: INFO
com.example.service: DEBUG
com.example.mapper: TRACE
动态修改(无需重启):
// 通过 Actuator 端点
@RestController
public class LogController {
@Autowired
private LoggingSystem loggingSystem;
@PostMapping("/log/level")
public void setLogLevel(@RequestParam String logger, @RequestParam String level) {
loggingSystem.setLogLevel(logger, LogLevel.valueOf(level));
}
}
访问:POST /actuator/loggers/com.example.service + Body {"configuredLevel": "DEBUG"}
3.Spring Boot Actuator 监控
关键端点:
management:
endpoints:
web:
exposure:
include: health,info,beans,conditions,env,metrics,mappings,loggers
常用调试场景:
/actuator/beans:查看 Bean 是否加载/actuator/conditions:查看自动配置生效情况/actuator/env:检查配置文件加载值/actuator/mappings:验证 Controller 映射/actuator/metrics:JVM 内存、线程、HTTP 请求统计
三、本地环境模拟
4.Docker Compose 一键模拟中间件
docker-compose.yml 示例:
version: '3.8'
services:
mysql:
image: mysql:8.0
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
redis:
image: redis:7-alpine
ports:
- "6379:6379"
kafka:
image: confluentinc/cp-kafka:latest
ports:
- "9092:9092"
environment:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
nacos:
image: nacos/nacos-server:v2.2.3
ports:
- "8848:8848"
environment:
MODE: standalone
启动命令:docker-compose up -d
优势:团队协作环境一致,CI/CD 可直接复用。
5.内存数据库快速测试
场景:单元测试无需连接真实数据库。
// 测试类配置
@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.yml")
public class UserServiceTest {
// 使用 H2 内存数据库
}
// application-test.yml
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
sql:
init:
mode: always
schema-locations: classpath:schema-h2.sql
四、代码增强与热部署
6.Spring Boot DevTools 热部署
配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
特性:
- 自动重启:classpath 文件变动触发应用重启(比冷启动快 80%)
- LiveReload:浏览器/前端资源自动刷新
- 远程调试:支持远程应用热更新
7.JRebel 商业热部署(终极方案)
优势:真正的热交换,无需重启,支持类结构修改(增删方法、字段)。
使用步骤:
- 安装 IDEA 插件
- 激活许可证
- 启动时选择 JRebel Debug
- 修改代码后 Ctrl + Shift + F9 编译当前文件即时生效
五、单元测试与 Mock
8.Spring Boot Test 最佳实践
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService; // 自动注入 Mock 对象
@Test
void testGetUser() throws Exception {
// 打桩
when(userService.getUser(1L)).thenReturn(new User("test"));
mockMvc.perform(get("/api/users/{id}", 1L))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("test"));
verify(userService, times(1)).getUser(1L);
}
}
9.Mock 中间件(Embedded)
@TestConfiguration
public class TestRedisConfig {
@Bean
public RedisServer redisServer() {
return RedisServer.newRedisServer().start(); // 嵌入式 Redis
}
}
支持组件:
- Embedded Redis:
com.github.kstyrc:embedded-redis - Embedded Kafka:
spring-kafka-test - Embedded MongoDB:
de.flapdoodle.embed:de.flapdoodle.embed.mongo
六、高级调试技巧
10.远程调试(Remote Debug)
场景:调试部署在测试环境/容器中的应用。
启动 JVM 参数:
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar
IDEA 配置:
- Run → Edit Configurations → + Remote JVM Debug
- Host:
测试服务器IPPort:5005 - 点击 Debug 图标连接
Docker 中开启:
FROM openjdk:17 EXPOSE 5005 CMD ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-jar", "app.jar"]
11.JMX 监控与 JVisualVM
启动参数:
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
JVisualVM 连接:jvisualvm → 右键 Local → JMX Connection → localhost:9999
功能:
- 查看堆内存、线程、类加载
- Sampler:CPU/内存采样分析
- Profiler:性能剖析
- MBeans:查看 Spring Beans 状态
12.Arthas 线上诊断神器
场景:生产环境无法远程调试,需动态诊断。
安装使用:
curl -O https://arthas.aliyun.com/arthas-boot.jar java -jar arthas-boot.jar # 选择 Java 进程
核心命令:
- watch:查看方法入参/返回值
watch com.example.service.UserService getUser '{params, returnObj}' -x 2 - trace:方法内部调用耗时追踪
trace com.example.service.UserService getUser -n 5 --skipJDKMethod false
- jad:反编译类查看源码
jad com.example.service.UserService
- ognl:执行 SpEL 表达式(查看/修改字段)
ognl '@com.example.config.GlobalConfig@STATIC_FIELD'
- dashboard:实时系统监控
七、多线程与异步调试
13.线程 Dump 分析
命令行:
# 查看 Java 进程 jps # 生成线程 Dump jstack <pid> > thread.dump
在线分析:https://fastthread.io/ 或 https://jstack.review/
关键状态:
- BLOCKED:等待锁,需定位死锁
- WAITING:等待条件唤醒
- TIMED_WAITING:Sleep 或定时等待
14.异步任务调试
@Service
public class AsyncService {
@Async
public CompletableFuture<User> asyncGetUser(Long id) {
// 断点会命中,但线程名是 task-1/task-2
return CompletableFuture.completedFuture(userMapper.selectById(id));
}
}
IDEA 调试技巧:
- All:查看所有线程堆栈
- Thread:仅查看当前线程(避免断点干扰其他线程)
- Mute Breakpoints:临时禁用断点,让程序运行到特定位置
八、网络与 HTTP 调试
15.MockServer 模拟外部 API
@BeforeEach
void setUp() {
mockServer = ClientAndServer.startClientAndServer(1080);
// 配置 Mock 响应
mockServer.when(
request()
.withMethod("POST")
.withPath("/api/payment")
).respond(
response()
.withStatusCode(200)
.withBody("{\"status\":\"success\"}")
);
}
16.Wireshark/TCPDump 抓包分析
# 抓取 8080 端口的 HTTP 请求 sudo tcpdump -i any -w capture.pcap port 8080 # 用 Wireshark 打开分析 wireshark capture.pcap
九、专项调试工具
17.内存溢出(OOM)分析
启动参数保留堆 Dump:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dump.hprof -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:/path/to/gc.log
分析工具:
- Eclipse MAT:分析堆 Dump,定位内存泄漏
- jhat:JDK 自带轻量分析
jhat dump.hprof
18.SQL 调试
MyBatis 日志:
logging:
level:
com.example.mapper: DEBUG # 打印 SQL 和参数
p6spy 监控:
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
</dependency>
自动打印 SQL 执行时间,识别慢查询。
十、调试效率提升技巧
19.IDEA 书签与断点技巧
- F11:匿名书签
- Ctrl + F11:带数字的书签(1-9)
- Ctrl + 1-9:跳转到数字书签
- 断点分组:右键断点 → Move to group,管理复杂场景
20.Spring Boot 调试模式
# 开启 DEBUG 日志 java -jar app.jar --debug # 查看自动配置报告 java -jar app.jar --debug > auto-config-report.txt # 启动时打印 Bean 创建过程 -Dlogging.level.org.springframework.beans.factory=DEBUG
总结:调试方法论
| 问题类型 | 首选工具 | 备选方案 |
|---|---|---|
| 业务逻辑错误 | IDEA 断点调试 | 日志 + 单元测试 |
| 环境问题 | Docker Compose | Embedded 组件 |
| 性能问题 | JVisualVM/Arthas | JProfiler(商业) |
| 生产问题 | Arthas | 远程 Debug |
| 并发问题 | jstack + 线程分析 | JMC(Java Mission Control) |
| 内存泄漏 | Eclipse MAT | JProfiler |
黄金法则:先在单元测试中复现,再用断点/日志定位,最后工具分析。调试是系统性工程,结合多种手段才能事半功倍。
到此这篇关于Java后端本地调试实用方法总结大全的文章就介绍到这了,更多相关Java后端本地调试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
