cglib基本コンセプト
Cglib プロキシはサブクラス・プロキシとも呼ばれ、問題のオブジェクトのサブクラスを実現するために、メモリ上にサブクラスオブジェクトを構築するために使用される。
標準オブジェクトの機能拡張.CGLibは、非常に低レベルのバイトコード技術を採用している。
テクニックは、あるクラスのサブクラスを作成し、そのサブクラスでメソッド・インターセプションを使用して、そのクラスのすべての親クラス・メソッドをインターセプトする。
を呼び出し、途中で横断的なロジックを織り交ぜる。しかし、継承が使われているため、最終的な
JDKダイナミックプロキシとCGLibダイナミックプロキシは、どちらもSprinPを実装している。
cglibの基本。
cglibデモケース
"https://..com/monkey0703"/p/.html#autoid-0-0-0
public class PersonService {
public PersonService() {
System.out.println("PersonServiceコンストラクト");
}
//このメソッドはサブクラスではオーバーライドできない
final public Person getPerson(String code) {
System.out.println("PersonService:getPerson>>"+code);
return null;
}
public void setPerson() {
System.out.println("PersonService:setPerson");
}
}
public class CglibProxyIntercepter implements MethodInterceptor {
@Override
public Object intercept(Object sub, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(" ...");
Object object = methodProxy.invokeSuper(sub, objects);
System.out.println(" ...");
return object;
}
}
public class Test {
public static void main(String[] args) { //クラスファイルをローカルディスクにプロキシする
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\code");
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback(new CglibProxyIntercepter());
PersonService proxy= (PersonService) enhancer.create(); proxy.setPerson(); proxy.getPerson("1");
}
}
...
PersonService:setPerson
...
PersonService:getPerson>>1
jdkデモケース
public class ProxyFactory implements InvocationHandler {
private Class target;
public <T>T getProxy(Class<T> c) {
this.target = c;
return (T)Proxy.newProxyInstance(c.getClassLoader(),c.isInterface()?new Class[]{c}:c.getInterfaces(),this);
}
@Override
public Object invoke(Object proxy , Method method , Object[] args) throws Throwable {
System.out.println("プロキシ実行実行");
if ( !target.isInterface() ){
method.invoke(target.newInstance(),args);
}
return "プロキシの戻り値";
}
public static void main(String[] args) {
// 生成されたプロキシ・クラスのバイトコード・ファイルを保存する
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
ProxyFactory proxyFactory = new ProxyFactory();
IProx proxyImpl = proxyFactory.getProxy(ProxImpl.class);
String result = proxyImpl.hello("hello word");
System.out.println(result);
System.out.println("---------");
IProx proxy = proxyFactory.getProxy(IProx.class);
result = proxy.hello("hello word");
System.out.println(result);
}
}
interface IProx{
String hello(String id);
}
class ProxImpl implements IProx{
@Override
public String hello(String id) {
System.out.println(id);
return null;
}
}
