Java/Guice/AbstractModule

1月 1, 2003 · Posted in Guice, Java · Comment 

単純な[[Module>Java/Guice/Module]]クラスの実装を利用すると、DIの定義を行うごとにbinder.???という定義を繰り返し記述しなければならない。
この問題を回避するために、[[AbstractModule>Java/Guice/AbstractModule]]を利用することができる。

import com.google.inject.AbstractModule;
import com.google.inject.Scopes;

public class SampleModule extends AbstractModule {
public void configure() {

bind(IService.class).to(Service.class);

bind(IService.class).to(Service.class).in(Scopes.SINGLETON);

Service service = new Service();
bind(IService.class).toInstance(service);

}
}

Java/Guice/ImplementedBy

1月 1, 2003 · Posted in Guice, Java · Comment 

デフォルトクラスの指定

ImplementedByアノテーションを利用して、そのインタフェースの実装クラスに対してデフォルトでInjectされるクラスを指定することができる。

import com.google.inject.ImplementedBy;

@ImplementedBy(Service.class)
public interface IService {
public void print();
}

Java/Guice/Module

1月 1, 2003 · Posted in Guice, Java · Comment 

モジュール

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;

public class SampleModule implements Module {
public void configure(Binder binder) {

// 通常の設定
binder.bind(IService.class).to(Service.class);

// Singletonパターンを適用
binder.bind(IService.class).to(Service.class).in(Scopes.SINGLETON);

Service service = new Service();
// 既存のインスタンスを利用した定義
binder.bind(IService.class).toInstance(service);

}
}

バインド

binder.bind(IService.class).to(Service.class);
IServiceのタイプの引数をとるメソッドには、実装クラスServiceをInjectする。

[[AbstractModule>Java/Guice/AbstractModule]]

上記の例ではBinderクラスのインスタンスbinderを定義ごとに記述しなければならないので、ちょっとめんどう。
[[AbstractModule>Java/Guice/AbstractModule]]を利用するとこの問題を回避することができる。

« 前ページへ次ページへ »