2012-05-16 3 views
3

Google Guice를 IOC 컨테이너로 사용하는 Java Swing 응용 프로그램을 만들고 있습니다. 구성 요소를 직접 주입하고 있지만 Guice가 외부에있는 구성 요소 을 작성하게합니다.Guice를 사용하여 스윙 구성 요소를 주입하는 모범 사례?

이 응용 프로그램은 다음과 같이 다소 같습니다

private Panel1 panel1; 
private Panel2 panel2; 

@Inject 
public class Application(Panel1 panel1, Panel2 panel2) { 
    this.panel1 = panel1; 
    this.panel2 = panel2; 
} 

이 질문 herehere 보면, 나는 구성 요소를 로더를 주입하는 대신 직접의 결론이되었다.

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

이 정보가 맞습니까? 이를 수행하기위한 모범 사례가 있습니까?

답변

4

'로더'를 사용하려면 com.google.inject.Provider을 구현해야합니다.

public class PanelModule extends AbstractModule { 

@Override 
protected void configure() { 
    bind(Panel1.class).toProvider(Panel1Provider.class); 
} 

private static class Panel1Provider implements Provider<Panel1> { 

    private Panel1 panel1; 

    @Override 
    public Panel1 get() { 
     try { 
      EventQueue.invokeAndWait(new Runnable() { 
       @Override 
       public void run() { 
        panel1 = new Panel1(); 
       } 
      }); 
     } catch (InvocationTargetException e) { 
      throw new RuntimeException(e); // should not happen 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
     } 
    } 
    return panel1; 
} 

또는 대안 당신은 단지 하나 개의 인스턴스가 필요한 경우 : 당신은 공급자에 의해 생성 된 객체를 삽입 할 수있는 모듈을 구성 할 수 있습니다 제공자에게 자신을 주입 할 필요가 없습니다 http://code.google.com/p/google-guice/wiki/InjectingProviders

의 예를 봐 구성 요소별로 인스턴스를 직접 유형에 바인딩 할 수 있습니다.

public class PanelModule extends AbstractModule { 

Panel1 panel1; 
Panel2 panel2; 

@Override 
protected void configure() { 

    try { 
     EventQueue.invokeAndWait(new Runnable() { 
      @Override 
      public void run() { 
       panel1 = new Panel1(); 
       panel2 = new Panel2(); 
      } 
     }); 
    } catch (InvocationTargetException e) { 
     throw new RuntimeException(e); // should not happen 
    } catch (InterruptedException e) { 
     Thread.currentThread().interrupt(); 
    } 

    bind(Panel1.class).toInstance(panel1); 
    bind(Panel2.class).toInstance(panel2); 
} 
관련 문제