Java后端本地调试实用方法总结大全

 更新时间:2026年01月14日 09:44:46   作者:廋到被风吹走  
这篇文章主要介绍了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 商业热部署(终极方案)

优势真正的热交换,无需重启,支持类结构修改(增删方法、字段)。

使用步骤

  1. 安装 IDEA 插件
  2. 激活许可证
  3. 启动时选择 JRebel Debug
  4. 修改代码后 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 Rediscom.github.kstyrc:embedded-redis
  • Embedded Kafkaspring-kafka-test
  • Embedded MongoDBde.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 配置

  1. Run → Edit Configurations → + Remote JVM Debug
  2. Host: 测试服务器IP Port: 5005
  3. 点击 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 ComposeEmbedded 组件
性能问题JVisualVM/ArthasJProfiler(商业)
生产问题Arthas远程 Debug
并发问题jstack + 线程分析JMC(Java Mission Control)
内存泄漏Eclipse MATJProfiler

黄金法则先在单元测试中复现,再用断点/日志定位,最后工具分析。调试是系统性工程,结合多种手段才能事半功倍。

到此这篇关于Java后端本地调试实用方法总结大全的文章就介绍到这了,更多相关Java后端本地调试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java对象为null的问题解决

    Java对象为null的问题解决

    如果一个对象为空,但是此时我们调用它的方法,就会遇到NullPointerException问题,本文主要介绍了Java对象为null的问题解决,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02
  • java根据模板导出PDF的详细实现过程

    java根据模板导出PDF的详细实现过程

    前段时间因为相关业务需求需要后台生成pdf文件,所以下面这篇文章主要给大家介绍了关于java根据模板导出PDF的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • SpringBoot实现EMQ设备的上下线告警

    SpringBoot实现EMQ设备的上下线告警

    EMQX 的上下线系统消息通知功能在客户端连接成功或者客户端断开连接,需要实现设备的上下线状态监控,所以本文给大家介绍了如何通过SpringBoot实现EMQ设备的上下线告警,文中有详细的代码示例,需要的朋友可以参考下
    2023-10-10
  • Java GenericObjectPool 对象池化技术之SpringBoot sftp 连接池工具类详解

    Java GenericObjectPool 对象池化技术之SpringBoot sftp 连接池工具类详解

    这篇文章主要介绍了Java GenericObjectPool 对象池化技术之SpringBoot sftp 连接池工具类详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • springboot启动类如何剔除扫描某个包

    springboot启动类如何剔除扫描某个包

    这篇文章主要介绍了springboot启动类如何剔除扫描某个包,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 解决org.springframework.context.ApplicationContextException报错的问题

    解决org.springframework.context.ApplicationContextException报错的

    这篇文章主要介绍了解决org.springframework.context.ApplicationContextException报错的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Java中一些基础概念的使用详解

    Java中一些基础概念的使用详解

    本篇文章是对在Java中一些基础概念的使用进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • java中-jar 与nohup的对比

    java中-jar 与nohup的对比

    这篇文章主要介绍了java中 -jar 与nohup的对比的相关资料,需要的朋友可以参考下
    2017-05-05
  • Apache POI将PPT转换成图片实例代码

    Apache POI将PPT转换成图片实例代码

    这篇文章主要介绍了Apache POI将PPT转换成图片实例代码,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • java17日期周期格式化处理方案

    java17日期周期格式化处理方案

    Java17引入了新的日期时间格式化模式B,用于表示一天中的时间段,如上午、下午、晚上等,该模式根据CLDR定义,在不同语言环境下,该模式的输出结果会有所不同,本文给大家介绍java17日期周期格式化处理方案,感兴趣的朋友跟随小编一起看看吧
    2025-01-01

最新评论