我正在开发一个使用 Google Guice 作为 IOC 容器的 Java Swing 应用程序。我直接注入组件,但这让 Guice在 EDT 之外创建组件。
该应用程序看起来有点像这样:
private Panel1 panel1;
private Panel2 panel2;
@Inject
public class Application(Panel1 panel1, Panel2 panel2) {
this.panel1 = panel1;
this.panel2 = panel2;
}
看看这里和这里的问题,我得出了注入加载程序而不是直接注入组件的结论。
private PanelLoader1 loader1;
private PanelLoader2 loader2;
private Panel1 panel1;
private Panel2 panel2;
@Inject
public class Application(PanelLoader1 loader1, PanelLoader2 loader2) {
this.loader1 = loader1;
this.loader2 = loader2;
loader1.load();
loader2.load();
this.panel1 = loader1.get();
this.panel2 = loader2.get();
}
public class PanelLoader {
private Panel panel;
public void load() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
panel = new Panel();
}
});
}
public Panel get() {
return panel;
}
}
它是否正确?这样做有什么最佳做法吗?