如果我想在构造函数依赖注入上使用注释
@Qualifier
,我会得到如下所示的内容:
public class Example {
private final ComponentExample component;
@Autowired
public Example(@Qualifier("someComponent") ComponentExample component) {
this.component = component;
}
}
我知道 Lombok 的注释可以减少样板代码,并且不必包含构造函数,如下所示:
@RequiredArgsConstructors(onConstructor=@__(@Inject))
但这仅适用于没有限定符的属性。
有人知道是否可以在
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
中添加限定符吗?
您可以像这样定义服务:
@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
}
}
假设您在项目的根目录中有一个像这样的
lombok.config
文件:
# 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
这是在 lombok 1.18.4 中引入的,我在我的博客文章中写了它,我很自豪地说我是推动该功能实现的主要驱动力之一。
@RequiredArgsConstructor
public class ValidationController {
//@Qualifier("xmlFormValidator")
private final Validator xmlFormValidator;
// Error code without edit lombok config
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
@Qualifier("anotherDao") UserDao userDao;
}
只需删除@Qualifier并更改变量的名称
// Works well
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
UserDao anotherDao;
}