
本文介绍如何通过动态代理优雅地为任意接口方法自动添加计时逻辑,避免在业务代码中重复编写 stopwatch 启停代码,提升可维护性与可观测性。
本文介绍如何通过动态代理优雅地为任意接口方法自动添加计时逻辑,避免在业务代码中重复编写 stopwatch 启停代码,提升可维护性与可观测性。
在日常开发中,对关键服务方法进行耗时监控是性能分析和问题排查的重要手段。但若在每个调用处手动嵌入 StopWatch(如循环内逐次启停),不仅代码冗余、易出错,还严重侵入业务逻辑。更优解是将计时能力横切(cross-cutting) 提取为通用机制——动态代理正是实现这一目标的轻量级方案。
以下是一个简洁可靠的 TimerProxy 实现,它基于 JDK 原生 java.lang.reflect.Proxy,无需额外依赖,适用于任何接口类型的服务:
public class TimerProxy {
private final Object delegate;
private static final Logger log = LoggerFactory.getLogger(TimerProxy.class);
public TimerProxy(Object delegate) {
this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
}
@SuppressWarnings("unchecked")
public <T> T getInterface(Class<T> intf) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return (T) Proxy.newProxyInstance(
loader,
new Class<?>[]{intf},
(proxy, method, args) -> {
StopWatch sw = new StopWatch();
sw.start();
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getTargetException(); // 保持原始异常栈
} finally {
sw.stop();
log.trace("Method '{}' executed in {} ms",
method.getName(), sw.getTotalTimeMillis());
}
}
);
}
}使用方式极为简单:假设你的服务类 SomeService 实现了接口 SomeServiceInterface,只需两行代码即可获得带自动计时能力的代理对象:
SomeServiceInterface original = new SomeService(); SomeServiceInterface timed = new TimerProxy(original).getInterface(SomeServiceInterface.class); // 后续所有方法调用均被自动计时 timed.processFoo(foo); // 日志自动输出:Method 'processFoo' executed in 123 ms
✅ 优势说明
- 零侵入:原始业务代码完全无需修改;
- 强类型安全:泛型
getInterface()确保编译期类型检查;- 异常透明:
InvocationTargetException被正确解包,不掩盖原始异常;- 线程安全:
StopWatch实例按调用创建,无共享状态,天然支持并发。
⚠️ 注意事项
- 该方案仅适用于接口类型(JDK Proxy 不支持类代理);若需代理具体类,可考虑 CGLIB 或 Spring AOP;
-
StopWatch来自 Spring Framework(org.springframework.util.StopWatch),请确保项目已引入spring-core; - 生产环境建议结合 Micrometer 或 Prometheus 进行指标采集,而非仅依赖日志——日志适合调试,指标更适合长期监控与告警。
综上,通过动态代理封装计时逻辑,既保持了代码的简洁性与可读性,又为系统可观测性奠定了坚实基础。这是一种小而美的工程实践,值得在工具类库或团队规范中沉淀复用。

















