Pau*_*Pau 29 java spring dependency-injection lombok
如果我想@Qualifier
在构造函数依赖注入上使用注释,我会有以下内容:
public class Example {
private final ComponentExample component;
@Autowired
public Example(@Qualifier("someComponent") ComponentExample component) {
this.component = component;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道lombok注释减少样板代码而不必包含构造函数如下:@RequiredArgsConstructors(onConstructor=@__(@Inject))
但这仅适用于没有限定符的属性.
有人知道是否可以添加限定符@RequiredArgsConstructor(onConstructor = @__(@Autowired))
?
Nik*_*hev 32
编辑:
这是FINALLY 可能的这样做!您可以拥有如下定义的服务:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你在项目的根目录中有这样的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
Run Code Online (Sandbox Code Playgroud)
这是最近在lombok 1.18.4中引入的,我在我的博客中写到了这一点,我很自豪地说我是推动该功能实现的主要推动力之一.
小智 12
您可以使用 spring 技巧通过使用所需的限定符命名字段而不使用 @Qualifier 注释来限定字段。
@RequiredArgsConstructor
public class ValidationController {
//@Qualifier("xmlFormValidator")
private final Validator xmlFormValidator;
Run Code Online (Sandbox Code Playgroud)
我还没有测试接受的答案是否运行良好,但我认为更干净的方法是将成员变量重命名为您想要限定的名称,而不是创建或编辑 lombok 的配置文件。
// Error code without edit lombok config
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
@Qualifier("anotherDao") UserDao userDao;
}
Run Code Online (Sandbox Code Playgroud)
只需删除@Qualifier并更改变量的名称
// Works well
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Foo {
UserDao anotherDao;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8852 次 |
最近记录: |