欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

spring中一个接口出现多个实现类时,调用时如何选择实现类

时间:2023-06-12

@Componentpublic interface Aorder { void say();}

@Componentpublic class Corder implements Aorder{ @Override public void say() { System.out.println("----------Corder------------"); }}

@Componentpublic class Dorder implements Aorder{ @Override public void say() { System.out.println("----------Border------------"); }}

@RunWith(SpringRunner.class)@SpringBootTest(classes = Application.class)public class OrderTest { @Autowired private MyOrderTest myOrderTest; @Test public void say(){ myOrderTest.test(); }}

 此时会报错,调用Aorder时不知道调用哪一个bean

@Resource

@Servicepublic class MyOrderTest { @Resource(type = Corder.class) private Aorder aorder; public void test(){ aorder.say(); }}

此时就能正常调用了,但是Corder,Dorder都实现Aorder,此时Corder,Dorder 都生成了bean

@Primary

@Component@Primarypublic class Corder implements Aorder{ @Override public void say() { System.out.println("----------Corder------------"); }}

Corder,Dorder都实现Aorder,此时只有Corder会生成bean,Dorder不会生成bean

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。