You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至Spring Boot 3后MDC.getCopyOfContextMap()返回null求助

解决Spring Boot 3中MDC失效问题

Spring Boot 3对追踪体系做了重构,默认不再直接绑定SLF4J的MDC,需额外配置实现Micrometer Tracing与MDC的联动。

步骤1:对齐依赖版本

避免版本不兼容问题,建议通过Spring Boot依赖管理引入组件,无需指定具体版本:

implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-tracing-bridge-brave'
implementation 'io.zipkin.reporter2:zipkin-reporter-brave'

步骤2:配置MDC同步

添加配置类,让Brave将追踪上下文同步至SLF4J的MDC:

import brave.slf4j.MDCScopeDecorator
import brave.Tracing
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class TracingConfig {
    @Bean
    fun mdcScopeDecorator(): MDCScopeDecorator {
        return MDCScopeDecorator.create()
    }

    @Bean
    fun tracing(mdcScopeDecorator: MDCScopeDecorator): Tracing {
        return Tracing.newBuilder()
            .scopeDecorator(mdcScopeDecorator)
            .build()
    }
}

步骤3:异步场景适配(如果涉及)

若代码中有异步任务,需配置任务装饰器传递MDC上下文:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.task.TaskExecutor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import org.slf4j.MDC
import java.util.concurrent.Runnable

@Configuration
class AsyncConfig {
    @Bean
    fun taskExecutor(): TaskExecutor {
        val executor = ThreadPoolTaskExecutor()
        executor.setTaskDecorator { runnable ->
            val contextMap = MDC.getCopyOfContextMap()
            Runnable {
                try {
                    contextMap?.let { MDC.setContextMap(it) }
                    runnable.run()
                } finally {
                    MDC.clear()
                }
            }
        }
        executor.initialize()
        return executor
    }
}

关键说明

  • Spring Boot 3默认用Micrometer Tracing替代了旧版Spring Cloud Sleuth,必须显式配置才能恢复MDC与追踪上下文的绑定。
  • 若无需分布式追踪,仅需基础MDC功能,可设置management.tracing.enabled=false或排除Micrometer Tracing相关依赖,但会丢失追踪能力。

内容的提问来源于stack exchange,提问作者newLearner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:39:58