Spring 5-@Bean方法的自定义限定符-NoSuchBeanDefinitionException

在工厂方法上,我一直在使用自定义@Qualifier和@Bean一起苦苦挣扎。看起来像这样:

@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER,ElementType.TYPE,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyCustomQualifierUno {
    String value() default "";
}

@Target({ElementType.FIELD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyCustomQualifierDos {
    String value() default "";
}

所需bean的工厂类由以下两种方法组成:

@Bean
@MyCustomQualifierUno
public RestTemplate getRestTemplate(SomeConfigUno config,SomeErrorHandlerUno errorHandler) {
        return new RestTemplateBuilder()
            (...)
            .build();
}

@Bean
@MyCustomQualifierDos
public RestTemplate getRestTemplate(SomeConfigDos config,SomeErrorHandlerDos errorHandler) {
        return new RestTemplateBuilder()
            (...)
            .build();
}

接下来,在Client类中,我进行了ctor注入,如下所示:

public SomeclientUno(@SomeQualifierUno RestTemplate 
    restTemplate) {
        this.restTemplate = restTemplate;
}

public SomeclientDos(@SomeQualifierDos RestTemplate 
    restTemplate) {
        this.restTemplate = restTemplate;
}

当我尝试运行该应用程序时,我得到: NoSuchBeanDefinitionException

一个有趣的事实是,当我添加一个扩展RestTemplate的专用类并将其放置在我的@CustomQualifier上时,我得到了异常,实际上现在有两个bean(即,现在确实考虑了@Bean方法)!

运行时间:IntelliJ Ultimate 2019.1 操作系统:Windows 10 64bit 的Java:1.8.0_191 春季版本:5.1.9

PS。这些“ Uno和Dos”是为了强调这一事实,它们是一些具体的类型,虽然无关紧要,但不要与@Qualifiers中的“ Uno和Dos”混淆了。

nihao10 回答:Spring 5-@Bean方法的自定义限定符-NoSuchBeanDefinitionException

这似乎太明显了,但是为什么要使用限定词呢? 假设您这样定义bean:

package android.util;

import android.support.annotation.NonNull;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class ArraySet<E extends Object> implements Collection<E>,Set<E> {
    private final HashSet<E> HASH_SET;

    public ArraySet(int capacity) {
        Log.e("ArraySet","WARNING,using fake array set!");
        HASH_SET = new HashSet<>(capacity);
    }

    @Override
    public int size() {
        return HASH_SET.size();
    }

    // Do this with all other methods as well: Chain them into HASH_SET.
}

这将使用限定符“ restTemplateUno”和“ restTemplateDos”注册Bean,因为“默认情况下,Bean名称将与方法名称相同”(有关详细信息,请参见Spring Docs)。

您现在可以将它们注入到客户端构造函数中,如下所示:

@Bean
public RestTemplate restTemplateUno(...) { ... }

@Bean
public RestTemplate restTemplateDos(...) { ... }

我希望这会有所帮助,并且我不会错过任何显而易见的让您开始考虑使用预选赛的东西。

本文链接:https://www.f2er.com/3104424.html

大家都在问