@Assisted 2つ以上付与した FactoryProvider の利用は、
@Assisted 付与時に、@Named でインジェクト対象を限定したように、
ユニークな文字列を指定する。
Names.named(String s) メソッドのようにコンフィグレーションで
約束するのではなく、FactoryProvider.newFactory で指定する
ファクトリクラスの実行で同じKey文字列指定の@Assisted を
付与することになる。
---------------------------------------------------
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
class FooImpl implements Foo{
private int num;
private String color;
private String fname;
private String sname;
@Inject
public FooImpl(int num,String color
,@Assisted("First") String fname
,@Assisted("Second") String sname){
this.num = num;
this.color = color;
this.fname = fname;
this.sname = sname;
}
:
}
---------------------------------------------------
ファクトリインターフェースにも@Assisted を付与
import com.google.inject.assistedinject.Assisted;
interface FooFactory{
public Foo create(@Assisted("First") String fname
,@Assisted("Second") String sname
);
}
----------------------------------------------------
FooFactoryを実行するインターフェースはそのまま
interface FooLookup{
public Foo lookup(String f,String s);
}
----------------------------------------------------
import com.google.inject.Inject;
/**
* FooFactoryを実行する役割の実装
*/
class FooLookupImpl implements FooLookup{
@Inject private FooFactory factory;
@Override
public Foo lookup(String fname,String sname){
return this.factory.create(fname,sname);
}
}
----------------------------------------------------
次のようにメソッドを用意できる
public static Foo createFoo(){
final Injector i = Guice.createInjector(new AbstractModule(){
@Override
protected void configure(){
binder().bind(int.class).toInstance(124);
binder().bind(String.class).toInstance("Red");
binder().bind(FooLookup.class).to(FooLookupImpl.class);
binder().bind(FooFactory.class)
.toProvider(FactoryProvider.newFactory(FooFactory.class,FooImpl.class));
}
}
);
return i.getInstance(FooLookupImpl.class).lookup("aaa","bbb");
}
public static Injector getInjector(){
final Injector i = Guice.createInjector(new AbstractModule(){
@Override
protected void configure(){
binder().bind(int.class).toInstance(124);
binder().bind(String.class).toInstance("Red");
binder().bind(FooLookup.class).to(FooLookupImpl.class);
binder().bind(FooFactory.class)
.toProvider(FactoryProvider.newFactory(FooFactory.class,FooImpl.class));
}
}
);
return i.createChildInjector(new AbstractModule(){
@Override
protected void configure(){
FooLookup f = i.getInstance(FooLookupImpl.class);
binder().bind(Foo.class).toInstance(f.lookup("AAA","BBB"));
}
}
);
}