1.JDK动态代理
UserDao类:
public interface UserDao { public void addUser(); }
UserDaoImpl类:
public class UserDaoImpl implements UserDao { @Override public void addUser() { System.out.println("添加用户"); } }
MyAspect切面:
public class MyAspect { public void check_permissions(){ System.out.println("检查权限"); } public void log(){ System.out.println("记录日志"); } }
JDK动态代理:
public class JdkProxy implements InvocationHandler { private UserDao userDao; public Object createProxy(UserDao userDao) { this.userDao = userDao; //1.类加载器 ClassLoader loader = JdkProxy.class.getClassLoader(); //2.被代理对象实现的所有接口 Class[] classes = userDao.getClass().getInterfaces(); //3.使用代理类进行增强,返回代理后的对象 return Proxy.newProxyInstance(loader, classes, this); } /** * @param proxy 被代理后的对象 * @param method 将要被执行方法的信息 * @param args 执行方法时需要的参数 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //创建切面 MyAspect myAspect = new MyAspect(); //前增强 myAspect.check_permissions(); //调用方法,并传参 Object obj = method.invoke(userDao, args); //后增强 myAspect.log(); return obj; } }
Test测试类:
public class Test { public static void main(String[] args) { //创建代理对象 JdkProxy jdkProxy = new JdkProxy(); //创建目标对象 UserDao userDao = new UserDaoImpl(); //从代理对象中获取增强后的对象 UserDao userDao1 = (UserDao) jdkProxy.createProxy(userDao); userDao1.addUser(); } }