jdk静态代理
interface Dao { void save(); } class DaoImpl implements Dao { @Override public void save() { System.out.println("save..."); } } class DaoProxy implements Dao{ private Dao target; public DaoProxy(Dao target) { this.target = target; } @Override public void save() { System.out.println("before..."); target.save(); System.out.println("after..."); } } public class StaticProxyTest { public static void main(String[] args) { DaoImpl target = new DaoImpl(); Dao userDao = new DaoProxy(target); userDao.save(); } }
jdk动态代理(代理接口)
interface Dao { void save(); } class DaoImpl implements Dao { @Override public void save() { System.out.println("save..."); } } public class DynamicProxyTest { public static void main(String[] args) { Object target = new DaoImpl(); /** * loader:业务对象的类加载器 * interfaces:业务对象实现的所有的接口,可直接指定业务类实现的接口 Class[] * h:InvocationHandler 对象,最终由它调用业务对象的方法 * public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) */ Dao dao = (Dao) Proxy.newProxyInstance(DaoImpl.class.getClassLoader(), new Class<?>[]{Dao.class}, new InvocationHandler() { /** * @param proxy 代理对象 * @param method 代理的方法对象 * @param args 方法调用时参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (method.getName().equals("save")) { System.out.println("before..."); result = method.invoke(target, args); System.out.println("after..."); } return result; } }); dao.save(); } }
cglib代理(代理类)
public class Dao { public void select() { System.out.println("select()"); } }
public class DaoProxy implements MethodInterceptor { /** * @param object 要进行增强的对象 * @param method 拦截的方法 * @param objects 参数列表,基本数据类型需要传入其包装类型 * @param proxy 对方法的代理,invokeSuper 方法表示对被代理对象方法的调用 */ @Override public Object intercept(Object object, Method method, Object[] objects, MethodProxy proxy) throws Throwable { System.out.println("Before Method Invoke"); proxy.invokeSuper(object, objects); System.out.println("After Method Invoke"); return object; } }
public static void main(String[] args) { DaoProxy daoProxy = new DaoProxy(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setCallback(daoProxy); Dao dao = (Dao) enhancer.create(); dao.select(); }