JDK动态代理
被代理接口
public interface Service {
void sayHello();
}
被代理实现类
public class ProxyService implements Service {
@Override
public void sayHello() {
System.out.println("hello");
}
}
控制器
public class MyHandler implements InvocationHandler{
private Object object;//通过构造函数传入 被代理的对象
public MyHandler(Object object) {
this.object = object;
}
/*
* @param proxy 被代理的对象
* @param method 被代理的方法
* @param args 被代理的方法的参数
* */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
method.invoke(object,args);
System.out.println("after");
return null;
}
}
测试类
public class Test {
public static void main(String[] args) {
Service service=new ProxyService();//被代理类的对象
Class cs=service.getClass();//被代理类的class
// 被代理类的类加载器 接口 handler
Service s=
(Service)Proxy.newProxyInstance(cs.getClassLoader(),
cs.getInterfaces(),
new MyHandler(service));
s.sayHello();
}
}
CGLIB动态代理
JDBC动态代理只能代理接口,有时候不方便,CGLIB动态代理则可以代理类。
被代理类
public class UserServiceImpl {
public void say(){
System.out.println("hello world");
}
}
拦截器
public class MyInterceptor implements MethodInterceptor {
private Object object;
public Object getInstance(Object object) {
this.object = object;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.object.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before");
Object object = methodProxy.invokeSuper(o, objects);
System.out.println("after");
return object;
}
}
测试类
public class Test {
public static void main(String[] args) {
MyInterceptor myInterceptor=new MyInterceptor();
UserServiceImpl userService= (UserServiceImpl) myInterceptor.getInstance(new UserServiceImpl());
userService.say();
}
}