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

如何为Maven依赖中的@Slf4j Logger配置@Around切面使其生效

问题解决方案

可以将切面应用到Maven依赖的第三方类上,你当前无法触发切面是Spring AOP的默认机制限制导致的,按以下说明调整即可:


根本原因

Spring默认使用基于动态代理的AOP实现,仅能拦截Spring容器托管的Bean的方法调用,ch.qos.logback.classic.Logger不属于Spring管理的Bean,所以普通Spring AOP根本无法拦截。要切第三方类必须使用完整的AspectJ织入能力,你已经配置了aspectj-maven-plugin,但配置存在兼容性和遗漏问题。


调整步骤

1. 修正切面配置

  • 去掉切面类上的@Component注解:AspectJ切面不归Spring容器管理,加了反而会被Spring当成普通AOP切面处理,产生冲突。
  • 如果你的GlobalConstants是Spring托管的Bean,需要给切面类加@Configurable注解,后续开启Spring的@EnableSpringConfigured支持,让AspectJ实例化的切面可以注入Spring容器中的Bean。

2. 升级aspectj-maven-plugin版本

你当前使用的1.7版本插件太旧,不支持JDK11,和你依赖的1.9.8版本AspectJ不兼容,会导致织入失败,替换为以下配置:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.14.0</version>
    <configuration>
        <complianceLevel>11</complianceLevel>
        <source>11</source>
        <target>11</target>
        <showWeaveInfo>true</showWeaveInfo>
        <verbose>true</verbose>
        <Xlint>ignore</Xlint>
        <encoding>UTF-8</encoding>
        <weaveDependencies>
            <weaveDependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
            </weaveDependency>
        </weaveDependencies>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. 补充依赖

增加Spring Aspects依赖适配AspectJ和Spring的集成:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>

4. 开启Spring配置

启动类增加以下注解开启AspectJ支持:

@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)

更推荐的替代实现

你要给日志追加bridgeRunId的需求完全不需要通过切面实现,直接用Logback原生的MDC机制即可,性能更高也没有兼容性问题:

  1. 在生成bridgeRunId的位置将值存入MDC:MDC.put("bridgeRunId", GlobalConstants.getBridgeRunId().toString());
  2. 在logback的日志格式配置中直接引用该值:{"bridgeRunId": "%X{bridgeRunId}"}%msg,即可实现所有日志自动拼接该字段的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:00:00