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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With