上面一篇主要讲了jdk提供的实现动态代理的方法,
本文主要接着上文给出了cglib动态代理基本写法。
传送门:JDK动态代理实践
里面共有2个新家的类,一个是用于实现invocationhandler(注意导包或者maven)
package study.JDKProxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class HelloServiceCgLib implements MethodInterceptor{
/**
* 创建代理对象唉
*/
private Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
//回调方法
enhancer.setCallback(this);
//创建代理对象
return enhancer.create();
}
/**
* 回调方法
*/
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
System.out.println("通过cglib来实现动态代理");
Object returnObj = arg3.invokeSuper(arg0, arg2);
return returnObj;
}
}
最后的测试方法:
@Test
public void testCgLibProxy() throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
Object service = Class.forName(HelloServiceImpl.class.getName()).newInstance();
//获取服务方法hello
Method method = service.getClass().getMethod("sayHello", String.class);
method.invoke(service, "June");
}
和原生JDK相比,cglib的动态代理可以不提供接口就可以使用。
赠人玫瑰手留余香~~