加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Refactor导致了循环引用

发布时间:2020-12-15 08:36:17 所属栏目:Java 来源:网络整理
导读:我在桌面应用程序中有这种代码 这只是一个包含按钮和那种东西的JPanel. class ApplicationPanel { private Listener listener; public ApplicationPanel(){ this.listener = new Listener(this); }} 这会将事件添加到上面JPanel中的控件. class Listener { p
我在桌面应用程序中有这种代码

这只是一个包含按钮和那种东西的JPanel.

class ApplicationPanel {

   private Listener listener;

   public ApplicationPanel(){
      this.listener = new Listener(this);
   }
}

这会将事件添加到上面JPanel中的控件.

class Listener {

   private ApplicationPanel panel;

   public Listener(ApplicationPanel panel){
      this.panel = panel;
   }
}

来电代码就是这样的

public void main(String[] args){
   ApplicationPanel panel = new ApplicationPanel();
}

如果我尝试应用依赖注入
和工厂(后来改为Guice)

class ApplicationPanel {

   private Listener listener;

   public ApplicationPanel(){
      this(new Listener());
   }

   public ApplicationPanel(Listener listener){
      this.listener = listener;
   }
}

class Listener {

   private ApplicationPanel panel;

   public Listener(){
      this(new ApplicationPanel());
   }

   public Listener(ApplicationPanel panel){
      this.panel = panel;
   }
}

来电代码就是这样的
如您所见,此代码中存在循环依赖关系
什么是解决这个问题的最佳方法?

public void main(String[] args){
   Listener listener = new Listener(panel);
   ApplicationPanel panel = new ApplicationPanel(listener);

}

解决方法

查看主题的 this blog post;鉴于您在guice模块中提供的绑定,guice足够聪明,可以检测循环引用,然后使用临时代理,以便解决注入问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读