gpt4 book ai didi

java - Cglib 方法拦截器是为每个类实例创建的吗?

转载 作者:行者123 更新时间:2023-12-02 11:12:29 25 4
gpt4 key购买 nike

我有以下通用 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;
}

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

最佳答案

是的,这一点你可以确定。然而,您的解决方案效率相当低,因为为每个实例都会生成一个新类。相反,您应该根据拦截器类型创建代理:

// 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();

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

关于java - Cglib 方法拦截器是为每个类实例创建的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com