【发布时间】:2012-09-04 10:07:26
【问题描述】:
我不确定我是否完全理解依赖注入背后的想法,尤其是使用 Guice。
我有一个相当大的 Swing 应用程序,我想介绍一下 guice,来解耦这个应用程序。 假设我在主类中有注射器
Guice.createInjector(new BindingModule());
Application app = injector.getInstance(Application.class);
app.run();
而且它有效。如果我有一些字段,比如说 JPanel,在 Application 类中,用 @Inject 注释然后它被注入。但是如果我在 Application 构造函数中手动创建一些东西 比示例中的 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所做的那样。
【问题讨论】: