I have a bunch of Processor. Some are of the same object type but have different configuration. I want to create a set of processor but choose which processor should go in which set. If there a way to do that using multibinding?
public class PostProcessorModule extends AbstractModule {
public static final String TYPE_A = "TypeA";
public static final String TYPE_B = "TypeB";
@Override
protected void configure() {
Multibinder<PostProcessor> typeASet =
Multibinder.newSetBinder(binder(), PostProcessor.class, Names.named("TypeASet"));
typeASet.addBinding().to(RandomizationPostProcessor.class); // Only want Type A
here
typeASet.addBinding().to(SecondPostProcessor.class);
Multibinder<PostProcessor> typeBSet =
Multibinder.newSetBinder(binder(), PostProcessor.class, Names.named("TypeBSet"));
typeASet.addBinding().to(RandomizationPostProcessor.class); // Only want Type B
here
typeASet.addBinding().to(SecondPostProcessor.class);
}
@Provides
@Singleton
@Named(TYPE_A)
public RandomizationPostProcessor getRandomizationPostProcessorA() {
return RandomizationPostProcessor.builder()
.toRandomize(3)
.build();
}
@Provides
@Singleton
@Named(TYPE_B)
public RandomizationPostProcessor getRandomizationPostProcessorB() {
return RandomizationPostProcessor.builder()
.toRandomize(10)
.build();
}
@Provides
@Singleton
public SecondPostProcessor getSecondPostProcessor() {
return new SecondPostProcessor();
}
}
public class Test {
@Inject
@Named("TypeASet")
private final Set<PostProcessor> setA;
@Inject
@Named("TypeBSet")
private final Set<PostProcessor> setB;
public void doSomething() {
...
}
}
RandomizationPostProcessor and SecondPostProcessor implements PostProcessor.
Does multibinding support this? I can't see any function like annotatedWith or similar which we have in normal bind() function. Is writing another function the only way to create custom set?
Sure, you can
addBindingto a specific key: