The Dragon Scroll

Be just and fear not.

googleのDIコンテナ登場。

DIコンテナと言えば、SpringFW、S2Containerが
思い浮かんできます。
そこに、Googleが新しいDIコンテナを加えたそうで。
GitHub - google/guice: Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.
Jungle Javaさんで知りました。
シンプルで軽量で、設定ファイルが不要な点がウリ。
guiceは、ジュースと読む。


GitHub - google/guice: Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.
>Guice was born purely out of use cases from one of Google's biggest (in every way) applications: AdWords
アドワーズで使うために、開発したようです。


Google ドキュメント - オンラインでドキュメントを作成/編集できる無料サービスです
ユーザガイドを読み拾ってみる。
guiceのコードを見る前にSpringのおさらい。

 public class SpringHello  {
   public static void main(String args[]){
      ApplicationContext contxt =
         new ClassPathXmlApplicationContext("applicationContext.xml");
      
      Hello hello = (Hello)contxt.getBean("hello");
      System.out.println( hello.getGreeting());
   }
}

public class Hello {
   public Hello() {}

   private String greeting;
   public String getGreeting() {
      return this.greeting;
   }
   public void setGreeting(String greeting) {
      this.greeting = greeting;
   }
}

後は、設定ファイルに注入するオブジェクトを記述する。

 
   
      
         こんにちは!
      
   

一方、Guiceの場合はこんな感じ。

 public class MyModule extends AbstractModule {
  protected void configure() {
    bind(Service.class)
      .to(ServiceImpl.class)
      .in(Scopes.SINGLETON);
  }
}

 public class Client {

  private final Service service;

  @Inject
  public Client(Service service) {
    this.service = service;
  }

  public void go() {
    service.go();
  }
}

bindメソッドで、インターフェースを実体クラスにバインドする。
そして、インジェクションする場所をアノテーション
書く。


SpringでのコンテキストからgetBeanするのにあたる例が、ガイドで
ぱっと見つからなかったので、テストコードを見ると、
こんな記述を発見。

public class BindingAnnotationTest extends TestCase {

  public void testAnnotationWithValueMatchesKeyWithTypeOnly() throws
      CreationException {
    Injector c = Guice.createInjector(new AbstractModule() {
      protected void configure() {
        bindConstant().annotatedWith(Blue.class).to("foo");
        bind(Foo.class);
      }
    });

    Foo foo = c.getInstance(Foo.class);

    assertEquals("foo", foo.s);
  }

  static class Foo {
    @Inject @Blue(5) String s; 
  }

  @Retention(RUNTIME)
  @BindingAnnotation
  @interface Blue {
    int value();
  }
}

createInjectorでバインドの設定を読み取って、getInstanceする。
要するに、Springが設定ファイルでやっていることを
bindというメソッドを使って書いているという感じでしょうか。
この辺は、Seaserとも異なるので、第三のDIコンテナという
感じがしますね。