Spring——JDK动态代理

我会带着你远行 2022-11-29 11:24 286阅读 0赞

动态代理

静态代理会为每一个业务增强都提供一个代理类, 由代理类来创建代理对象, 而动态代理并不存在代理类, 代理对象直接由代理生成工具动态生成.

JDK动态代理

  • JDK动态代理是使用 java.lang.reflect 包下的代理类来实现. JDK动态代理动态代理必须要有接口.
  • JDK动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理,需要指定一个类加载器,然后生成的代理对象实现类的接口或类的类型,接着处理额外功能.
  • JDK动态代理制能对实现了接口的类生成代理,而不是针对类

    //定义两个dao接口
    public interface DeptDao {

    1. public int addDept();
    2. public int updateDept();

    }

  1. //实现dao接口中的两个方法
  2. public class DeptDaoImpl implements DeptDao{
  3. public int addDept() {
  4. System.out.println("添加部门到数据库中");
  5. return 0;
  6. }
  7. public int updateDept() {
  8. System.out.println("更新部门信息");
  9. return 0;
  10. }
  11. }

实现代理

  1. //jdk动态代理:代理类实现一个接口
  2. public class DyProxy<T> implements InvocationHandler {
  3. public DyProxy() {
  4. }
  5. public DyProxy(T target) {
  6. this.target = target;
  7. }
  8. //声明属性:接收所代理的对象
  9. private T target;
  10. public T getTarget() {
  11. return target;
  12. }
  13. public void setTarget(T target) {
  14. this.target = target;
  15. }
  16. //执行invoke方法就是执行所代理对象的方法
  17. //proxy:所代理的对象
  18. //method:所要执行的方法
  19. //args:要执行方法的参数
  20. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  21. //动态代理对象执行的所代理对象的方法
  22. //声明变量来存放执行代理对象方法的返回值
  23. Object o=null;
  24. System.out.println("动态代理开始执行……");
  25. try {
  26. o=method.invoke(target, args);
  27. } catch (IllegalAccessException e) {
  28. e.printStackTrace();
  29. System.out.println("动态代理对象执行方法时发成异常");
  30. } catch (IllegalArgumentException e) {
  31. e.printStackTrace();
  32. System.out.println("动态代理对象执行方法时发成异常");
  33. } catch (InvocationTargetException e) {
  34. e.printStackTrace();
  35. System.out.println("动态代理对象执行方法时发成异常");
  36. } finally {
  37. System.out.println("动态代理执行结束!");
  38. }
  39. return o;
  40. }
  41. }

测试

  1. public class TestProxy {
  2. public static void main(String[] args) {
  3. //创建代理对象
  4. UserDaoProxy userDaoProxy=new UserDaoProxy();
  5. //声明一个实现类
  6. DeptDaoImpl ddi=new DeptDaoImpl();
  7. //使用代理
  8. InvocationHandler deptProxy=new DyProxy<DeptDaoImpl>(ddi);
  9. DeptDao proxy= (DeptDao) Proxy.newProxyInstance(DeptDao.class.getClassLoader(),
  10. new Class[]{DeptDao.class},
  11. deptProxy);
  12. proxy.addDept();
  13. //还可以给UserDaoImpl做代理
  14. UserDaoImpl udimpl=new UserDaoImpl();
  15. InvocationHandler userProxy=new DyProxy<UserDaoImpl>(udimpl);
  16. //把代理对象 和被代理的绑定在一起
  17. UserDao proxy2=(UserDao)Proxy.newProxyInstance(UserDao.class.getClassLoader(),
  18. new Class[]{UserDao.class},
  19. userProxy);
  20. proxy2.registerUser();
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,286人围观)

还没有评论,来说两句吧...

相关阅读

    相关 代理-jdk动态代理

    1、基于接口的实现,要jdk动态代理的类必须要实现一个接口; 2、中介类:实现了InvocationHandler,并重写这个接口的 方法(public Object inv