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

Spring Boot 3.2.2中@Timed注解无法生成Micrometer指标求助

解决Spring Boot 3.2.2中Micrometer @Timed注解不生效问题

问题诊断

你的配置存在两个核心问题导致@Timed注解不生效:

  1. private方法无法被AOP拦截:Spring的AOP基于代理实现,private方法不会被代理增强,因此标注在doBusiness()上的@Timed无法生效。
  2. 缺少@Timed注解的启用配置:Spring Boot 3.x中需要显式启用Micrometer注解的AOP支持,否则注解不会被处理。

修复步骤

1. 优化依赖(避免版本冲突)

spring-boot-starter-actuator已经包含了micrometer-core,无需手动指定该依赖,移除pom.xml中手动添加的micrometer-core依赖:

<!-- 移除以下冗余依赖 -->
<!--
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-core</artifactId>
    <version>1.12.2</version>
</dependency>
-->

2. 启用Micrometer注解支持

在Spring Boot应用的主类上添加@EnableTimed注解,开启@Timed的AOP代理增强:

import io.micrometer.core.annotation.EnableTimed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableTimed
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

3. 修正private方法的@Timed使用

由于AOP无法拦截private方法,需将doBusiness()改为public,或把业务逻辑抽入单独的@Component类(推荐)。修改后的控制器示例:

import io.micrometer.core.annotation.Timed;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Timed(value = "first.timer", description = "Time taken by GET method")
    @GetMapping("/apiEndpoint")
    public String helloWorld() {
        doBusiness();
        return "Hello world called!";
    }

    // 修改为public方法,让AOP可以拦截
    @Timed(value = "second.timer", description = "Time taken by business method")
    public void doBusiness() {
        // 模拟长耗时任务
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

4. 验证结果

启动应用后,多次调用/apiEndpoint,然后访问以下端点查看metrics:

  • GET /actuator/metrics/first.timer:查看API接口的计时数据
  • GET /actuator/metrics/second.timer:查看业务方法的计时数据

Spring Boot 3.2.2官方文档核心要点

Spring Boot官方文档中关于Micrometer注解的说明集中在Actuator的Metrics章节,核心内容:

  • 必须通过@EnableTimed启用注解驱动的计时器功能
  • @Timed可标注在类或public方法上,类级注解会应用到所有public方法
  • private方法无法通过AOP拦截,若需监控需手动创建Timer实例或调整方法可见性
  • 可通过配置项微调注解行为:
management:
  metrics:
    annotations:
      enabled: true  # 显式启用注解支持(默认已开启,可省略)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:07:46