弹簧无法自动接线,有一个以上的``类型的豆 [英] Spring Couldn't autowired,there is more than one bean of `` type

查看:126
本文介绍了弹簧无法自动接线,有一个以上的``类型的豆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:我有一个基本接口和两个实现类.

Here is my question:I have a base interface and two implementation class.

并且Service类在基本接口上具有依赖项,代码如下:

And a Service class has a dependencies on the base interface, the code is like this:

@Component
public interface BaseInterface {}


@Component
public class ClazzImplA implements  BaseInterface{}


@Component
public class ClazzImplB implements  BaseInterface{}


配置如下:


And the configuration is like this :

@Configuration
public class SpringConfig {
    @Bean
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}


服务类依赖于基本接口,将通过一些业务逻辑决定自动装配哪个实现.代码如下:


The service class has dependencies on the base interface will decide to autowire which Implementation by some business logic.And the code is like this:

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

IDEA引发异常:无法自动装配.BaseInterface类型的bean不止一个.

And the IDEA throws a exception:Could not autowire.There is more than one bean of BaseInterface type.

尽管可以使用@Qualifier来解决它,但是在这种情况下,我无法选择依赖项类.

Although it can be solved by using @Qualifier,but in this situation I can't choose the dependencies class.

@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;

我尝试阅读spring文档,它提供了 Constructor-based dependency injection ,但我仍然对该问题感到困惑.

I tried to read the spring document and it provide a Constructor-based dependency injection but I'm still confused by the problem.

有人可以帮助我吗?

推荐答案

Spring在您在配置类中声明的2个bean之间是混淆的,因此您可以将@Qualifier注释与@Autowired一起使用,通过指定来消除混淆将要连接的是哪个确切的bean,请将这些修改应用于您的配置类

Spring is confused between the 2 beans you have declared in you configuration class so you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired, apply these modifications on your configuration class

@Configuration
public class SpringConfig {
    @Bean(name="clazzImplA")
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean(name="clazzImplB")
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

然后在@autowired注释

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    @Qualifier("the name of the desired bean")
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

这篇关于弹簧无法自动接线,有一个以上的``类型的豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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