You need to enable JavaScript to run this app. Java自定义TimeCounter注解实现方法耗时统计问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义TimeCounter注解实现方法耗时统计问题咨询

自定义@TimeCounter注解实现方案(无Spring AOP依赖)

首先明确:注解本身仅作为功能标记,不承载执行逻辑,我们采用AspectJ编译期字节码织入的方案实现功能,该方案完全不依赖Spring组件,符合产品约束。

第一步:定义@TimeCounter注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD) // 仅允许标记在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时保留注解信息
public @interface TimeCounter {
}

第二步:编写注解逻辑处理切面

用AspectJ实现切面,捕获所有标记了@TimeCounter的方法执行,完成日志输出:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
public class TimeCounterAspect {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    @Around("@annotation(TimeCounter)") // 拦截所有标记@TimeCounter的方法
    public Object countMethodTime(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取方法名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        
        // 2. 输出开始时间
        LocalDateTime startTime = LocalDateTime.now();
        System.out.printf("[TimeCounter] 方法[%s] 执行开始时间:%s%n", methodName, startTime.format(FORMATTER));
        
        long startMs = System.currentTimeMillis();
        Object result = null;
        try {
            // 执行原方法逻辑
            result = joinPoint.proceed();
        } finally {
            // 3. 输出结束时间和耗时
            LocalDateTime endTime = LocalDateTime.now();
            long costMs = System.currentTimeMillis() - startMs;
            System.out.printf("[TimeCounter] 方法[%s] 执行结束时间:%s%n", methodName, endTime.format(FORMATTER));
            System.out.printf("[TimeCounter] 方法[%s] 总执行耗时:%dms%n", methodName, costMs);
        }
        return result;
    }
}

第三步:配置编译期织入(无需运行时依赖Spring)

我们在编译阶段就把切面逻辑织入到目标方法中,运行时完全不需要额外框架支持:

Maven项目配置示例

在pom.xml中添加AspectJ编译插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.14.0</version>
            <configuration>
                <complianceLevel>1.8</complianceLevel>
                <source>1.8</source>
                <target>1.8</target>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjrt</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.9.7</version>
    </dependency>
</dependencies>

运行效果示例

执行TimeCounterDemo的trackMyTimeSpentUsingAnnotation方法后,输出如下:

[TimeCounter] 方法[com.example.TimeCounterDemo.trackMyTimeSpentUsingAnnotation] 执行开始时间:2024-05-20 14:30:00.123
[TimeCounter] 方法[com.example.TimeCounterDemo.trackMyTimeSpentUsingAnnotation] 执行结束时间:2024-05-20 14:30:02.456
[TimeCounter] 方法[com.example.TimeCounterDemo.trackMyTimeSpentUsingAnnotation] 总执行耗时:2333ms

可选轻量方案(无字节码增强)

如果不想引入AspectJ,也可以用JDK动态代理/CGLIB封装目标类,在调用方法前后判断是否有@TimeCounter注解执行耗时统计,缺点是需要通过代理对象调用方法才会生效,无需修改编译配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 23:36:03