Suppose I want to inject a map of keys to matching instances. With Spring, I could do it very easily
@Bean
// injecting a collection of all beans matching the MyDomainObject type
public Map<String, MyDomainObject> map(List<MyDomainObject> objects) {
Map<String, MyDomainObject> map = new HashMap<>();
for (MyDomainObject object : objects) {
map.put(object.getKey(), object);
}
return map;
}
It’s very flexible. If MyDomainObject
is an abstract type, I can simply declare new implementations (for example, writing new MyDomainObjectImpl
s and marking them as @Component
s), and the map bean will 1) automatically pick up new beans while 2) keeping its signature
I am hard pressed to achieve the same with Dagger (which I have to switch to since I’m now doing frontend, still in Java)
How can I do a similar thing in Dagger?
ChatGPT suggested this
@Module
public abstract class TypeModule {
@Binds
@IntoSet
abstract Type provideType1(TypeImpl1 typeImpl1);
@Binds
@IntoSet
abstract Type provideType2(TypeImpl2 typeImpl2);
// Add more @Binds methods for other Type implementations
}
Do I really have to create a new bean declaration for each new implementation and mark it with @Into(List/Set...)
?