我不确定我完全理解依赖注入背后的想法,特别是使用Guice。使用guice注入对象
我有相当大的swing应用程序,我想介绍guice来解耦这个应用程序。 假设我有喷射器主类
Guice.createInjector(new BindingModule());
Application app = injector.getInstance(Application.class);
app.run();
和它的作品。如果我有一些字段,比如JPanel,在Application类中,用@Inject注释,然后注入它。但是如果我在应用程序构造函数 中手动创建一些比JTree更好的例子,将不会被注入(假设所有内容都已正确配置)。
class Application {
@Inject JPanel mainPanel //this will be injected
JPanel otherPanel;
public Application() {
otherPanel = new MyNewPanel();
mainPanel.add(otherPanel);
}
}
class MyNewPanel extends JPanel {
@Inject JTree tree; //this will not be injected
public MyNewPanel() {
add(tree);
}
}
我的问题是,我是否需要注入所有注入的控制guice的对象。 我无法打破控制,就像我用otherPanel
做的那样。