Video in progress

Strong Junior 🌱 Spring

When you use Lombok's @RequiredArgsConstructor, why is the @Qualifier on the field ignored?

When Lombok generates the constructor, by default it doesn't copy the field's @Qualifier to the parameter. Spring looks at the parameter, finds several matching beans, and either fails or picks the @Primary one.

📖 Answer

@Service
@RequiredArgsConstructor
class NotificationService {

    @Qualifier("smsSender")
    private final MessageSender sender;   // there are two beans: smsSender, emailSender
}

The constructor Lombok generates is roughly this:

NotificationService(MessageSender sender) {   // no @Qualifier!
    this.sender = sender;
}

Spring injects through the constructor and sees no qualifier on the parameter. The result:

  • with no @Primary bean, NoUniqueBeanDefinitionException and the application won't start;
  • with a @Primary bean, a different bean quietly arrives, and the email goes out instead of the SMS. That's much worse, because it may not show up in tests either.

The fix is in a lombok.config file (at the project root):

lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value

Now Lombok copies these annotations to the constructor parameter. @Value has the same problem.

Other ways: write the constructor by hand, or match the field name to the bean name. When there are several candidates, Spring also looks at the parameter name. But that depends on the -parameters compiler flag and is brittle, so an explicit qualifier is more reliable.