是否为每个类实例创建了Cglib方法拦截器?

时间:2018-05-25 10:45:04

标签: java cglib

我有以下通用的cglib方法拦截器实现:

public class EntityInterceptor<T, PK> implements MethodInterceptor{

    private EntityChangeType changeType;
    private T entity;
    private GenericCrudMapper<T,PK> mapper;

    public EntityInterceptor(T entity, GenericCrudMapper<T, PK> mapper){
        this.entity = entity;
        this.mapper = mapper;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        // pass through
        return proxy.invoke(entity, args);
    }

    public void setEntityChangeType(EntityChangeType changeType){
        this.changeType = changeType;
    }

    public void saveChanges(){
        // @todo
    }

}

使用如下:

@Override
    public Airport get(String id) {
        Airport airport = airportMapper.findById(id);
        if(airport != null){
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Airport.class);
            enhancer.setCallback(new EntityInterceptor<>(airport, airportMapper));
            airport = (Airport) enhancer.create();
            return airport;
        }
        return airport;
    }

我可以安全地假设上面创建的方法拦截器将按照增强类实例进行实例化(换句话说,在分配方法拦截器时,它们不在所有类实例之间共享)?

1 个答案:

答案 0 :(得分:1)

是的,你可以肯定这一点。但是,由于为每个实例生成了一个新类,因此您的解决方案效率很低。相反,您应该根据拦截器类型创建代理:

// Do once
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(realObject.getClass());
enhancer.setCallbackType(Airport.class);
Class classForProxy = enhancer.createClass();

// Do for each instance
Enhancer.registerCallbacks(classForProxy, new Callback[]{new EntityInterceptor<>(airport, airportMapper});
Object createdProxy = classForProxy.newInstance();

这样,您可以为所有代理实例重用单个类。