簡體   English   中英

使用guice注入對象

[英]Injecting object using guice

我不確定我一般是否完全理解依賴注入,尤其是使用Guice。

我有一個很大的swing應用程序,並且我想介紹guice,以解耦該應用程序。 假設我主班有噴油器

Guice.createInjector(new BindingModule());
Application app = injector.getInstance(Application.class);
app.run();

而且有效。 如果我有某個字段,可以說是在Application類中使用@Inject注釋的JPanel,然后將其注入。 但是,如果我在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所做的otherPanel

在“依賴注入”范式中, 所有注入的對象必須在注入容器的控制下 ,這是容器實際上可以將對象的實例注入到注入點@Inject注釋)的唯一方法。

當使用new運算符實例化對象實例時, 該對象實例將不受注入容器的控制 (它是由您而不是容器創建的)。 因此,即使您在該新對象實例中具有注入點,該容器也不知道它們,因此它無法將任何候選注入對象注入該對象實例的注入點(因為正如我已經說過的,無法控制)。

因此,請回答幾個問題: 是的,如果要自動注入所有對象,則需要將所有對象置於容器(Guice)的控制之下 您可能遇到的任何使您按照問題中的含義進行注入的工作都會違反控制反轉規則。

如果要或必須使用新的,可以使用提供者guice提供者或按需注入guice注入 `注入器注入器= Guice.createInjector(...);

MyNewPanel myNewPanel = new MyNewPanel();
injector.injectMembers(myNewPanel);`

上面的代碼可以略作重寫以使用標准注入。

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 );

或者在Application構造函數中使用MyNewPanel。 但這並沒有那么耦合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM