28 Kasım 2022 Pazartesi

CGLIB Kullanımı - Kullanmayın Deprecate Edildi

Giriş
Açıklaması şöyle
The cglib library is widely used and well-known in many frameworks, but it has been deprecated recently.
Açıklaması şöyle. Yani JDK ile gelen Proxy sınıfının çok benzeri. Ancak CGLIB final metodlar'ı intercept edemiyor.
Enhancer: Similar to the Proxy in the JDK way. It uses create() method to create a proxy instance on which you make a call

MethodInterceptor: Similar to InvocationHandler in the JDK way. The intercept() method will be called when you make a call on the proxy instance
Örnek
Elimizde şöyle bir Interceptor olsun
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class UserServiceCglibInterceptor implements MethodInterceptor {
  private Object realObj;

  public UserServiceCglibInterceptor(Object realObject) {
    super();
    this.realObj = realObject;
  }

  @Override
  public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    Object result = null;
    if (args != null && args.length > 0 && args[0] instanceof User) {
      User user = (User)args[0];
      ...
      result = method.invoke(realObj, args);
    }
    return result;
  }
}
Şöyle yaparız
import org.springframework.cglib.proxy.Enhancer;

UserService target = new UserServiceImpl();
MethodInterceptor interceptor = new UserServiceCglibInterceptor(target);

Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(interceptor);
UserService proxy = (UserService) enhancer.create();
proxy.addUser(user);



Hiç yorum yok:

Yorum Gönder