EachBean injecting from other EachBean #6630
-
By way of context, imagine that there are two classes @EachBean(MyDuplicationConfig.class)
public class Radio {
Radio(MyDuplicationConfig conf) {
// Do something
}
} But now the question is, how do I get this @Factory
public class VehicleFactory {
@Inject
@Named("copy1")
Radio radio1;
@Inject
@Named("copy2")
Radio radio2;
@EachBean(MyDuplicationConfig.class)
Vehicle createVehicle(MyDuplicationConfig conf) {
if (conf.getName().equals("copy1"))
return new Vehicle(radio1);
return new Vehicle(radio2);
}
} And that seems to work, however then you end up with some duplication (need to inject the radio twice) and you also now need to be extra careful when adding/removing/renaming the names of the duplicate instances. From what I've seen it would appear that there is a mechanism for getting around this limitation by using the ApplicationContext directly. @Factory
public class VehicleFactory {
@Inject
ApplicationContext ctx;
@EachBean(MyDuplicationConfig.class)
Vehicle createVehicle(MyDuplicationConfig conf) {
return new Vehicle(ctx.getBean(Radio.class, Qualifiers.byName(prop.getName())));
}
} Much more concise, but is this safe? It's working in the limited testing I've performed, but my fear is that the I believe that the simplest and safest approach would be to allow @EachBean(MyDuplicationConfig.class)
public class Vehicle {
Vehicle(MyDuplicationConfig conf, @Named(conf.getName()) Radio radio) {
// Do something
}
} Can this be done? Is it possible for class annotated as EachBean to inject from another class annotated as EachBean? The above doesn't compile and variations on that idea that I've tried either don't compile or don't work. What would be the suggest solution of achieving this result? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We use this pattern all the time in Micronaut modules, try use |
Beta Was this translation helpful? Give feedback.
We use this pattern all the time in Micronaut modules, try use
@Parameter Radio radio