Google guice で、List をインジェクションする時によく使うのが、com.google.inject.TypeLiteral
Java8 lambda の Consumer をインジェクションすることをやれば、条件分岐によるメソッド実行を
一括管理の記述ができると思った。
まず、分岐ではなく、ただの Consumer をインジェクションする例。
Injector injector = Guice.createInjector(new AbstractModule(){ @Override protected void configure(){ binder().bind(new TypeLiteral<Consumer<?>>(){}) .toInstance(e->{ System.out.println(e); }); } });
Injector で生成されるクラスのメソッドで、Consumer を実行
@Inject Consumer<String> consumer; public void exec(){ consumer.accept("accept! on Foo::exec()"); }
AbstractModule の configure の中で if 文を書くか、if 文による Moduleインスタンスを Guice.createInjector
に渡す方法を考えるかもしれないが、
あまり整理できると思えない。
今のところ、Mapを使用することぐらいしか思いつかない。
Map<String, Consumer<String>> map = new HashMap<>(); map.put("1", e->{ System.out.println("Test 1 : " + e); }); map.put("2", e->{ System.out.println("Test 2 : " + e); }); String key = "2"; Injector injector = Guice.createInjector(new AbstractModule(){ @Override protected void configure(){ binder().bind(new TypeLiteral<Consumer<String>>(){}).toInstance(map.get(key)); } });
条件毎の実装クラス定義を作らなくて済むだけでもありがたいのかも知れない。