绪论:以下三种java实现动态代理的的方式,分别为基于jdk的,基于cglib的和基于javassist的,其中需要注意的两点
一:基于jdk实现的动态代理需要实现父类,而其他两种不需要
二:其中基于cglib的需要额外的jar包依赖,pom的依赖如下
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
为了方便,测试类写在了一起,代码如下:
package info.lumanman.mybatis.entry.proxy;
public class People implements PeopleInterface{
public String getInfo(int age){
System.out.println("执行中--张三的年龄:"+age);
return "张三的年龄:"+age;
}
}
package info.lumanman.mybatis.entry.proxy;
public interface PeopleInterface {
public String getInfo(int age);
}
package info.lumanman.mybatis.entry.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.junit.Test;
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class ProxyTest {
@Test
public void testJdkProxy() {
final People people=new People();
PeopleInterface proxy=(PeopleInterface) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),
People.class.getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理前");
Object result=method.invoke(people, args);
System.out.println("代理后");
return result;
}
});
String result=proxy.getInfo(18);
System.out.println("执行结果:"+result);
}
@Test
public void testCglibProxy() {
People people=new People();
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(people.getClass());
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("前置处理");
Object result=proxy.invokeSuper(obj, args);
System.out.println("后置处理");
return result;
}
});
People proxy=(People)enhancer.create();
String result= proxy.getInfo(19);
System.out.println("执行结果:"+result);
}
@Test
public void testJavassistProxy() throws Exception {
ProxyFactory factory=new ProxyFactory();
factory.setSuperclass(People.class);
factory.setFilter(new MethodFilter() {//过滤器可以对方法进行过滤,不加也行
public boolean isHandled(Method m) {
//if(m.getName().equals("execute")){
return true;
//}
//return false;
}
});
factory.setHandler(new MethodHandler() {
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
System.out.println("前置处理");
Object result=proceed.invoke(self, args);
System.out.println("后置处理");
return result;
}
});
Class<?> c=factory.createClass();
People proxy=(People) c.newInstance();
String result= proxy.getInfo(19);
System.out.println("执行结果:"+result);
}
}
参考:《mybatis技术内幕》