Can an injector inject all implementations of an interface? #303
-
interface MyFunc {
void something();
}
@Inject
class MyFuncImpl1 implements MyFunc {
@Override
public void something() {
}
}
@Inject
class MyFuncImpl2 implements MyFunc {
@Override
public void something() {
}
}
@Provides
public String useInject(Set<MyFunc> myFuncSet) {
// get all MyFunc implement
return "";
} |
Beta Was this translation helpful? Give feedback.
Answered by
eduard-vasinskyi
Jan 24, 2024
Replies: 1 comment 2 replies
-
Hi, @zzl221000 An Injector can inject all implementations of a class, but to do so, it needs to be instructed how to resolve conflicting bindings. For your case, the easiest way to do this is by instructing Injector to use Set to resolve conflicting bindings. bindIntoSet(Key.of(MyFunc.class), Key.of(MyFuncImpl1.class));
bindIntoSet(Key.of(MyFunc.class), Key.of(MyFuncImpl2.class)); The resulting class would look something like this: public class TestModule extends AbstractModule {
@Override
protected void configure() {
bindIntoSet(Key.of(MyFunc.class), Key.of(MyFuncImpl1.class));
bindIntoSet(Key.of(MyFunc.class), Key.of(MyFuncImpl2.class));
}
public interface MyFunc {
void something();
}
@Inject
static class MyFuncImpl1 implements MyFunc {
@Override
public void something() {
System.out.println("1");
}
}
@Inject
static class MyFuncImpl2 implements MyFunc {
@Override
public void something() {
System.out.println("2");
}
}
@Provides
public String useInject(Set<MyFunc> myFuncSet) {
for (MyFunc myFunc : myFuncSet) {
myFunc.something();
}
// get all MyFunc implement
return "some string";
}
public static void main(String[] args) {
Injector injector = Injector.of(new TestModule());
String instance = injector.getInstance(String.class);
System.out.println(instance);
}
} When the 2
1
some string |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
zzl221000
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, @zzl221000
An Injector can inject all implementations of a class, but to do so, it needs to be instructed how to resolve conflicting bindings.
For your case, the easiest way to do this is by instructing Injector to use Set to resolve conflicting bindings.
You can do this by overriding the
configure()
method of a Module and specifying that you want your bindings to be provided into a set:The resulting class would look something like this: