Java/Guice/AbstractModule
単純な[[Module>Java/Guice/Module]]クラスの実装を利用すると、DIの定義を行うごとにbinder.???という定義を繰り返し記述しなければならない。
この問題を回避するために、[[AbstractModule>Java/Guice/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
デフォルトクラスの指定
ImplementedByアノテーションを利用して、そのインタフェースの実装クラスに対してデフォルトでInjectされるクラスを指定することができる。
例
@ImplementedBy(Service.class)
public interface IService {
public void print();
}
Java/Guice/Module
モジュール
例
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);
}
}
バインド
IServiceのタイプの引数をとるメソッドには、実装クラスServiceをInjectする。
[[AbstractModule>Java/Guice/AbstractModule]]
上記の例ではBinderクラスのインスタンスbinderを定義ごとに記述しなければならないので、ちょっとめんどう。
[[AbstractModule>Java/Guice/AbstractModule]]を利用するとこの問題を回避することができる。

