是否可以在@RequredArgsConstruction (onConstruction =@__(@Autowired))中添加限定符?

如果我想在一个构造函数依赖注入上使用注释 @Qualifier,我会有如下内容:

public class Example {


private final ComponentExample component;


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

我知道龙目岛关于减少样板代码的注释,不需要包含构造函数,如下所示:。

有人知道是否可以在 @RequiredArgsConstructor(onConstructor = @__(@Autowired))中添加限定符吗?

58224 次浏览

EDIT:

It is FINALLY POSSIBLE to do so! You can have a service defined like this:

@Service
@RequiredArgsConstructor
public class SomeRouterService {


@NonNull private final DispatcherService dispatcherService;
@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

This was recently introduced in latest 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.

You may use spring trick to qualify field by naming it with desired qualifier without @Qualifier annotation.

@RequiredArgsConstructor
public class ValidationController {


//@Qualifier("xmlFormValidator")
private final Validator xmlFormValidator;

I haven't test whether the accepted answer works well, but instead of create or edit lombok's config file, I think the cleaner way is rename the member variable to which name you want to qualifier.

// Error code without edit lombok config
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
@Qualifier("anotherDao") UserDao userDao;
}

Just remove @Qualifier and change your variable's name

// Works well
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
UserDao anotherDao;
}