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

Cglib Method Interceptor是否为每个增强类实例单独实例化?

结论:是的,每个增强类实例都会对应单独的EntityInterceptor实例,不会在实例间共享

你完全可以放心——从你提供的代码实现和使用方式来看,每个通过CGLIB生成的增强对象,都会绑定一个独立的EntityInterceptor实例,不会出现多个代理实例共享同一个拦截器的情况,原因如下:

1. 拦截器实例是每次创建代理时全新初始化的

看你的get方法代码:

@Override 
public Airport get(String id) { 
    Airport airport = airportMapper.findById(id); 
    if(airport != null){ 
        Enhancer enhancer = new Enhancer(); 
        enhancer.setSuperclass(Airport.class); 
        // 这里每次都会new一个全新的EntityInterceptor实例
        enhancer.setCallback(new EntityInterceptor<>(airport, airportMapper)); 
        airport = (Airport) enhancer.create(); 
        return airport; 
    } 
    return airport; 
}

每次调用get方法生成代理对象时,你都会新建一个EntityInterceptor实例,并把当前查询到的airport和对应的airportMapper传入构造方法。这个新的拦截器实例只会和本次create()生成的代理对象绑定。

2. CGLIB的回调绑定逻辑保证了实例独立性

CGLIB的Enhancer在调用create()时,会将你设置的Callback(也就是这里的EntityInterceptor)与生成的代理实例关联起来。每个代理实例都会持有自己的回调引用,不会和其他代理实例共享同一个回调对象。

额外提醒

只有当你把EntityInterceptor做成可复用的单例、或者在多个代理创建逻辑中复用同一个拦截器实例时,才会出现共享的情况。但你的代码里完全没有这种操作,所以当前的实现是安全的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:43:31