Spring学习之设计模式,动态代理和gclib动态代理

传统的代理模式是静态代理,也就是在方法区域中写入方法。

而动态代理的作用是,不修改实现类的代码,能够在代码的前后或者抛出异常的前后执行某个方法。

动态代理类的实现

//Interface
public interface UserServiceInter {
void save();
void delete();
void modify();
void search();
}
//entity
public class UserService implements UserServiceInter{
public void save(){
System.out.println("保存");
} public void delete(){
System.out.println("删除");
} public void modify(){
System.out.println("修改");
} public void search(){
System.out.println("查询");
}
}
//代理类以及测试类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class UserServiceProxyFactory implements InvocationHandler{
private UserService us; public UserServiceProxyFactory(UserService us) {
this.us = us;
} public UserServiceInter getUserServiceProxy(){
UserServiceInter us=(UserServiceInter) Proxy.newProxyInstance(UserService.class.getClassLoader(),
UserService.class.getInterfaces() , this);
return us;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before invoke");
Object invoke=method.invoke(us, args);
System.out.println("after invoke");
return invoke;
} public static void main(String[] args) {
UserServiceProxyFactory factory=new UserServiceProxyFactory(new UserService());
UserServiceInter us=factory.getUserServiceProxy();
us.delete();
}
}

运行结果:

Spring学习之设计模式,动态代理和gclib动态代理

注意:Proxy.newInsatance()的三个参数,第一个是实现类或者Interface的类加载器,第二个是实现类的Interface数组,第三个是Invocation接口的实现类

接收使用实现类的Interface接口进行接收。

CGlib动态代理

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
//spring整合了cglib的Enhancer类,cglib代理实质是一个继承代理
public class UserServiceProxyFactory2 implements MethodInterceptor{
public UserServiceInter getUserServiceProxy(){
Enhancer en=new Enhancer();//该类帮我们生成代理对象
en.setSuperclass(UserService.class);//代理类
en.setCallback(this);//代理做什么
UserServiceInter us=(UserServiceInter) en.create();//创建代理对象
return us;
} @Override
public Object intercept(Object proxyobj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
System.out.println("before");
//调用原有方法
Object ret=methodProxy.invokeSuper(proxyobj, arg);
System.out.println("after");
return ret;
}
public static void main(String[] args) {
UserServiceInter us=new UserServiceProxyFactory2().getUserServiceProxy();
us.delete();
}
}
上一篇:java静态代理和JDK动态代理


下一篇:java学习笔记(中级篇)—JDK动态代理