SpringBoot:Could not autowire there is more than one bean of xx type

早过忘川 提交于 2020-01-26 07:47:02

1.美图

在这里插入图片描述

2.背景

代码如下

package com.git.hui.boot.conditionbean.example.conditional;

import java.util.function.Supplier;

/**
 * Created by @author yihui in 22:03 18/10/17.
 */
public class RandDataComponent<T> {

    private Supplier<T> rand;

    public RandDataComponent(Supplier<T> rand) {
        this.rand = rand;
    }

    public T rand() {
        return rand.get();
    }

}

配置类如下

package com.git.hui.boot.conditionbean.example.conditional;

import com.git.hui.boot.conditionbean.example.conditional.condition.RandBooleanCondition;
import com.git.hui.boot.conditionbean.example.conditional.condition.RandIntCondition;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Random;

/**
 * Created by @author yihui in 22:05 18/10/17.
 */
@Configuration
public class ConditionalAutoConfig {

    @Bean
    @Conditional(RandIntCondition.class)
    public RandDataComponent<Integer> randIntComponent() {
        return new RandDataComponent<>(() -> {
            Random random = new Random();
            return random.nextInt(1024);
        });
    }

    @Bean
    @Conditional(RandBooleanCondition.class)
    public RandDataComponent<Boolean> randBooleanComponent() {
        return new RandDataComponent<>(() -> {
            Random random = new Random();
            return random.nextBoolean();
        });
    }
}

然后引入报错
在这里插入图片描述
导致这个错误的原因通常是注入的类型有其他的实现类,所以IDEA提示注入的时候会冲突。比如我的项目出现这个错误的原因是项目中新增了一个定制的插件,这个插件里重写了这个类。

因此出现这个问题的时候可以有两种办法解决。

3.给不同的实现标注名字

使用Qulifier注解标注

@Autowired
@Qualifier(name = 'testService1')
private TestService testService;

4.使用@Primary

@Component
@Primary
public class TestService{}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!