Search code examples
javaspringdependency-injectionlombok

Is it possible to add qualifiers in @RequiredArgsConstructor(onConstructor = @__(@Autowired))?


If I wanted to use the annotation @Qualifier on a constructor dependency injection, I would have something like the following:

public class Example {

    private final ComponentExample component;

    @Autowired
    public Example(@Qualifier("someComponent") ComponentExample component) {
        this.component = component;
    }
}

I know Lombok's annotations to reduce boilerplate code and don't have to include a constructor would be as follows: @RequiredArgsConstructors(onConstructor=@__(@Inject)) but this only works with properties without qualifiers.

Anyone know if it is possible to add qualifiers in @RequiredArgsConstructor(onConstructor = @__(@Autowired))?


Solution

  • You can have a service defined like this:

    @Service
    @RequiredArgsConstructor
    public class SomeRouterService {
    
       @Qualifier("someDestination1") @NonNull private final SomeDestination someDestination1;
       @Qualifier("someDestination2") @NonNull private final SomeDestination someDestination2;
    
       public void onMessage(Message message) {
           // some code to route stuff based on something to either destination1 or destination2
       }
    
     } 
    

    Provided that you have a lombok.config file like this in the root of the project:

    # Copy the Qualifier annotation from the instance variables to the constructor
    # see https://github.com/rzwitserloot/lombok/issues/745
    lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
    lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
    

    This was introduced in lombok 1.18.4, I wrote about it in my blogpost, and I am proud to say I was one of the main driving forces pushing for the implementation of the feature.