一、動態代理引入
package cn2; public interface IUserDAO { /** * 登录方法 */ public void login(); /** * 注册方法 */ public void register(); } package cn2; public class UserDAOImpl implements IUserDAO { @Override public void login() { System.out.println("用户登录"); } @Override public void register() { System.out.println("用户注册"); } } package cn2; public class Test { public static void main(String[] args) { IUserDAO dao = new UserDAOImpl(); dao.register(); dao.login(); } }
用戶註冊
用戶登入
如果我要給每個方法增加權限校驗和日誌記錄權限的話,那麼程式碼實作如下:
package cn2; public interface IUserDAO { /** * 登录方法 */ public void login(); /** * 注册方法 */ public void register(); } package cn2; public class UserDAOImpl implements IUserDAO { @Override public void login() { System.out.println("用户登录"); } @Override public void register() { System.out.println("用户注册"); } } package cn2; public class UserDAOImpl2 implements IUserDAO { private void actionCheck(){ System.out.println("权限检查"); } private void record(){ System.out.println("日志记录"); } @Override public void login() { this.actionCheck(); System.out.println("登录"); this.record(); } @Override public void register() { this.actionCheck(); System.out.println("注册"); this.record(); } } package cn2; public class Test { public static void main(String[] args) { IUserDAO dao = new UserDAOImpl2(); dao.register(); dao.login(); } }
reee
日誌記錄權限檢查登入日誌記錄public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)最終會呼叫InvocationHandler的方法
Object invoke(Object proxy,Method method,Object[] args)
package cn2; public interface IUserDAO { /** * 登录方法 */ public void login(); /** * 注册方法 */ public void register(); } package cn2; public class UserDAOImpl implements IUserDAO { @Override public void login() { System.out.println("用户登录"); } @Override public void register() { System.out.println("用户注册"); } } package cn2; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } /** *返回动态代理对象 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("权限检查"); Object invoke = method.invoke(target, args); System.out.println("日志记录"); return invoke; } } package cn2; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { //使用动态代理之前 IUserDAO dao = new UserDAOImpl(); dao.register(); dao.login(); System.out.println("-------------------"); //使用动态代理之后 IUserDAO proxy = (IUserDAO)Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), new MyInvocationHandler(dao)); proxy.register(); proxy.login(); } }---------權限檢查用戶註冊日誌記錄權限檢查用戶登入日誌記錄