spring中怎么注入两个实现同一个接口的bean-CSDN论坛

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring中怎么注入两个实现同一个接口的bean-CSDN论坛相关的知识,希望对你有一定的参考价值。

取别名。实现类的注解中加上不一样的别名。用@resource(别名)获取 参考技术A 不能 会报错的

Spring 同一接口注入多个bean实现

如果同一个接口有多个bean实现类,spring在运行时会出现如下异常

required a single bean, but 2 were found:
marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

@Primary的意思是在众多相同的bean中,优先使用用@Primary注解的bean.而@Qualifier这个注解则指定某个bean有没有资格进行注入。

@Component
@Primary

 

@Autowired

 

@Component

@Qualifier("fjaoidfj")

 

@Autowired

@Qualifier("fjaoidfj")

 

以上是关于spring中怎么注入两个实现同一个接口的bean-CSDN论坛的主要内容,如果未能解决你的问题,请参考以下文章

spring容器注入一个接口的两个实现类

Spring(SpringBoot)--同类型多个bean的注入--@Primary/@Qualifier

Spring应用--实现InitializingBean接口

Spring 同一接口注入多个bean实现

在spring项目中,普通类注入获取Bean,实现ApplicationContextAware接口

spring依赖注入中获取JavaBean