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

问题描述 投票:0回答:3

如果我想在构造函数依赖注入上使用注释

@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))
中添加限定符吗?

java spring dependency-injection lombok
3个回答
241
投票

您可以像这样定义服务:

@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 中引入的,我在我的博客文章中写了它,我很自豪地说我是推动该功能实现的主要驱动力之一。

  • 详细讨论该问题的博客文章
  • github上的原始
  • 问题
  • 还有一个小型
  • github 项目来查看它的实际效果

34
投票
您可以使用 spring 技巧来限定字段,方法是使用所需的限定符命名它,而不使用 @Qualifier 注释。

@RequiredArgsConstructor public class ValidationController { //@Qualifier("xmlFormValidator") private final Validator xmlFormValidator;
    

6
投票
我还没有测试接受的答案是否运行良好,但我认为更干净的方法是将成员变量重命名为您想要限定的名称,而不是创建或编辑 lombok 的配置文件。

// 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; }
    
© www.soinside.com 2019 - 2024. All rights reserved.