是否可以在@RequiredArgsConstructor(onConstructor = @__(@Autowired)) 中添加限定符? [英] Is it possible to add qualifiers in @RequiredArgsConstructor(onConstructor = @__(@Autowired))?

查看:135
本文介绍了是否可以在@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.

这篇关于是否可以在@RequiredArgsConstructor(onConstructor = @__(@Autowired)) 中添加限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆