Java 使用guice注入对象

Java 使用guice注入对象,java,guice,Java,Guice,我不确定我是否完全理解依赖注入背后的思想,尤其是使用Guice 我有一个相当大的swing应用程序,我想介绍guice来解耦这个应用程序。 假设我在主类中有注入器 Guice.createInjector(new BindingModule()); Application app = injector.getInstance(Application.class); app.run(); 它是有效的。若我在应用程序类中有一些字段,比如JPanel,用@Inject注释,那个么它就被注入了。但如果

我不确定我是否完全理解依赖注入背后的思想,尤其是使用Guice

我有一个相当大的swing应用程序,我想介绍guice来解耦这个应用程序。 假设我在主类中有注入器

Guice.createInjector(new BindingModule());
Application app = injector.getInstance(Application.class);
app.run();
它是有效的。若我在应用程序类中有一些字段,比如JPanel,用@Inject注释,那个么它就被注入了。但如果在中,我在应用程序构造函数中手动创建一些东西 不会注入示例中的JTree(假设所有内容都配置正确)

我的问题是,我是否需要将所有注入的对象都控制在要注入的guice中。
我不能像我使用
其他面板时那样破坏控件

如果您想或必须使用新的,您可以使用提供程序或 按需注射。 `Injector=Guice.createInjector(…)

上面的代码可以稍微重写以使用标准注入

class Application {

      final JPanel mainPanel;

      final JPanel otherPanel;


      @Inject
      public Application( @Named("main") JPanel mainPanel, @Named("other") JPanel otherPanel) {
          this.otherPanel = otherPanel;
          this.mainPanel = mainPanel;
          mainPanel.add(otherPanel);             
      }

}  

class MyNewPanel extends JPanel { 


      @Inject JTree tree;  

      public MyNewPanel() {

           add(tree);
      }

}
由于注入了两个不同的面板,因此可以通过命名来区分它们,即使用annotatedWith绑定它们

binder.bind( JPanel.class ).annotatedWith( Names.named( "other" ).to( MyNewPanel.class );

或者在应用程序构造函数中使用MyNewPanel。但这有点不那么解耦。

在依赖项注入范例中,所有注入的对象都必须控制注入容器,这是容器实际上可以将对象实例注入到注入点的唯一方法(
@inject
注释)

当您使用
new
操作符实例化对象实例时,该对象实例不受注入容器的控制(它是由您创建的,而不是容器)。因此,即使在新的对象实例中有注入点,容器也不知道它们,因此它不能将任何注入候选注入到该对象实例的注入点中(因为,正如我已经说过的,它已经失控)

因此,用几句话来回答:是的,如果希望自动注入所有对象,则需要将它们置于容器(Guice)的控制之下。任何黑客,你可能会出现让注射工作的方式,你在你的问题意味着将打破规则

class Application {

      final JPanel mainPanel;

      final JPanel otherPanel;


      @Inject
      public Application( @Named("main") JPanel mainPanel, @Named("other") JPanel otherPanel) {
          this.otherPanel = otherPanel;
          this.mainPanel = mainPanel;
          mainPanel.add(otherPanel);             
      }

}  

class MyNewPanel extends JPanel { 


      @Inject JTree tree;  

      public MyNewPanel() {

           add(tree);
      }

}
binder.bind( JPanel.class ).annotatedWith( Names.named( "other" ).to( MyNewPanel.class );