it编程 > 编程语言 > Java

通过案例理解Spring中静态代理

5人参与 2025-12-09 Java

参考https://www.jb51.net/program/3545702mr.htm

无论是静态代理还是动态代理,都有四大角色:

  1. 抽象角色:一般会使用接口或者抽象类来解决
  2. 真实角色:被代理的角色
  3. 代理角色:代理真实角色,一般会做一些附属操作
  4. 客户:访问代理对象的人

中介租房案例

首先,定义一个接口(rent),房东类(host)实现该接口,并输出自己房子的相关信息。

//租房
public interface rent {
    public  void rent();
}
//房东
public class host implements rent{
    public void rent() {
        system.out.println("我的房子是蓝色的,准备出租房子!");
    }
}

房东将房子交给中介,此时的中介相当于代理类(proxy)

代理类在不修改被代理对象功能 (host类的rent方法) 的基础上,可以对代理类进行扩展(增加seehouse、fare方法)

public class proxy implements rent{
    private host host;
    public proxy(){ }
    public proxy(host host){
        this.host=host;
    }
    public void rent() {
        seehouse();
        host.rent();
        fare();
    }
    //看房
    public void seehouse(){
        system.out.println("中介带你看房子");
    }
    }
    //收费
    public void fare(){
        system.out.println("收中介费");
    }
}

客户购房不用面对房东,只需与中介对接。

public class client {
    public static void main(string[] args) {
        host host=new host(); //房东要出租房子
        //代理,中介帮房东租房子,但是代理角色一般会有一些附属操作
        proxy proxy=new proxy(host);
        //客户不用面对房东,直接找中介租房即可
        proxy.rent();
    }
}

上述代码就实现了静态代理,客户只需面向代理类操作即可。

运行截图

缺点:静态代理中,每个真实对象都会拥有一个代理类,这样将会十分繁琐。

如果采用静态代理,当有100个房东时,我们将要编写100个代理类,这种处理方法明显不妥。因此我们可以使用动态代理,编写一个代理工具类,该类并未指明代理的真实对象是哪一个。

public class dynamicproxy {
    public static object getproxyinstance(object target){
        return proxy.newproxyinstance(
            target.getclass().getclassloader(),
            target.getclass().getinterfaces(),
            (proxy, method, args)->{
                object result = method.invoke(target,args);
                return result;
            }
        );
    }
}
public class client {
    public static void main(string[] args) {
        rent proxyinstance1 = (rent) dynamicproxy.getproxyinstance(
                new host1());
        proxyinstance1.rent();
        rent proxyinstance2 = (rent)dynamicproxy.getproxyinstance(
                new host2());
        proxyinstance2.rent();
    }
}

到此这篇关于通过案例理解spring中静态代理的文章就介绍到这了,更多相关spring静态代理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

Spring中静态代理与动态代理的实现及区别对比分析

12-09

mybatis-plus分表实现案例(附示例代码)

12-09

Java调用DeepSeek API的8个高频坑与解决方法

12-09

Springboot请求和响应相关注解及使用场景分析

12-09

Spring Boot 与 Spring Cloud

12-09

Java线程池配置原则与实战解析

12-09

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论