Java / Micronaut Interview questions
How do you troubleshoot a Micronaut bean that fails to inject due to ambiguous qualifiers?
An ambiguous injection error, where Micronaut reports multiple candidate beans for a single injection point, happens when more than one bean implements the same injected type and none is marked as the one to prefer.
public interface NotificationSender {} @Singleton public class EmailSender implements NotificationSender {} @Singleton public class SmsSender implements NotificationSender {}
Injecting NotificationSender directly at this point fails to resolve. The fix is to disambiguate explicitly, using one of a few approaches:
- Named qualifiers: annotate each implementation with
@Named("email")and@Named("sms"), then inject with a matching@Namedqualifier at the call site. - Custom qualifier annotations for stronger typing than string-based
@Named. - @Primary on one implementation, marking it the default when no explicit qualifier is given.
- Injecting a collection such as
List<NotificationSender>instead of a single instance, when you actually want all implementations.
Reading the actual error message matters here; Micronaut's compile-time and startup validation typically names the exact injection point and the competing bean classes, which is usually enough to identify which of these four fixes applies without guesswork.
More Related questions...