Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Refactor led to a Circular reference

I have this sort of code in a desktop app

This is just a JPanel that contains buttons and that sort of thing.

class ApplicationPanel {

   private Listener listener;

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

This adds the events to the controls in the JPanel above.

class Listener {

   private ApplicationPanel panel;

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

Caller code would be like this

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

If I try to apply dependency injection And factories(later to be changed for 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;
   }
}

Caller code would be like this As you can see, there's a circular dependency in this code Whats the best way to solve this?

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

}
like image 496
Rodrigo Dellacqua Avatar asked Feb 21 '26 01:02

Rodrigo Dellacqua


1 Answers

Check out this blog post on the topic; guice is smart enough, given the bindings you provide in your guice Module, to detect the circular reference and then use a temporary proxy so that the injection can be resolved.

like image 115
Karl Rosaen Avatar answered Feb 23 '26 14:02

Karl Rosaen