是否可以在@RequiredArgsConstructor(onConstructor = @__(@ Autowired))中添加限定词? [英] Is it possible to add qualifiers in @RequiredArgsConstructor(onConstructor = @__(@Autowired))?
问题描述
如果我想在构造函数依赖项注入中使用注释 @Qualifier
,我将具有以下内容:
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;
}
}
我知道Lombok的注释可以减少样板代码,并且不必包含构造函数,如下所示: @RequiredArgsConstructors(onConstructor = @ __(@ Inject))
但这仅适用于属性没有预选赛.
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.
任何人都知道是否可以在 @RequiredArgsConstructor(onConstructor = @__(@ Autowired))
中添加限定符吗?
Anyone know if it is possible to add qualifiers in @RequiredArgsConstructor(onConstructor = @__(@Autowired))
?
推荐答案
这样做是最后 可能!您可以定义如下服务:
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
}
}
在项目的根目录中提供了一个像这样的lombok.config文件:
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 1.18.4中引入的,我在博客中写道.我很自豪地说我是推动该功能实现的主要推动力之一.
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.
- github上的问题
- 还有一个小的 github项目,以查看实际效果
这篇关于是否可以在@RequiredArgsConstructor(onConstructor = @__(@ Autowired))中添加限定词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!