标签:throwable ade *** get targe http nts rda target
小贴士:以下内容纯属个人观点,如有不当请指出并谅解
import java.lang.reflect.Proxy;
Proxy可以动态代理一个对象
写一个代理工厂类ProxyFactory:
package com.zhangpn.serviceImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory implements InvocationHandler { private Object target;//这是被动态代理的对象 public Object createProxyIntance(Object target) {//通过调用此方法,将被代理目标传入并且返回代理对象,在此invoke方法会被回调 this.target = target; return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("******调用动态被代理对象之前做相关处理******"); method.invoke(target, args); System.out.println("------调用动态被代理对象之后做相关处理------\n"); return null; } }
写两个被代理类:
第一个User:
package com.zhangpn.daoImpl; import com.zhangpn.dao.UserDao; public class UserDaoImpl implements UserDao { public void save() { System.out.println("UserDaoImpl save success!"); } }
其实现的接口:
package com.zhangpn.dao; public interface UserDao { public void save(); }
第二个Student:
package com.zhangpn.daoImpl; import com.zhangpn.dao.StudentDao; public class StudentDaoImpl implements StudentDao { public void save() { System.out.println("StrudentDaoImpl save success!"); } }
其实现的接口:
package com.zhangpn.dao; public interface StudentDao { public void save(); }
测试运行:
package com.zhangpn.Test; import com.zhangpn.dao.StudentDao; import com.zhangpn.dao.UserDao; import com.zhangpn.daoImpl.StudentDaoImpl; import com.zhangpn.daoImpl.UserDaoImpl; import com.zhangpn.serviceImpl.ProxyFactory; public class Test { public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(); UserDao userDao = (UserDao) factory.createProxyIntance(new UserDaoImpl()); userDao.save(); StudentDao studentDao = (StudentDao) factory.createProxyIntance(new StudentDaoImpl()); studentDao.save(); } }
Spring中AOP:Proxy动态代理浅解析(被代理对象必须实现接口)
标签:throwable ade *** get targe http nts rda target
原文地址:https://www.cnblogs.com/batj/p/9129648.html