最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

@Autowired一個接口有多個實現(xiàn)類的情況

 更新時間:2025年10月21日 16:27:44   作者:qq_18800269  
本文介紹了Spring中@Autowired注解的注入原理,默認(rèn)按類型(byType)注入,當(dāng)存在多個實現(xiàn)類時,會報錯,可以通過修改變量名或配合@Qualifier注解,指定注入具體實現(xiàn)類,變?yōu)榘疵Q(byName)注入

@Autowired一個接口有多個實現(xiàn)類

@Autowired是spring的注解

默認(rèn)使用的是byType的方式向Bean里面注入相應(yīng)的Bean。

例如:

@Autowired
private UserService userService;

這段代碼會在初始化的時候,在spring容器中尋找一個類型為UserService的bean實體注入,關(guān)聯(lián)到userService的引入上。

但是如果UserService這個接口存在多個實現(xiàn)類的時候,就會在spring注入的時候報錯,具體如下:

public class UserService1 implements UserService
public class UserService2 implements UserService

當(dāng)存多個UserService的實現(xiàn)類時,錯誤信息如下:

2016-08-05 14:53:53,795 ERROR [org.springframework.test.context.TestContextManager] - <Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@14a2f921] to prepare test instance [UserServiceTest@3c87521]>
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private yjc.demo.service.UserService UserServiceTest.userService; nested exception is he[yjc.demo.service.UserService] is defined: expected single matching bean but found 2: userService1,userService2

拋出了org.springframework.beans.factory.BeanCreationException,而原因是注入的時候發(fā)現(xiàn)有2個匹配的bean,但是不知道要注入哪一個:

expected single matching bean but found 2: userService1,userService2

如何應(yīng)對多個實現(xiàn)類的場景呢

看一下代碼:

@Autowired
private UserService userService1;


@Autowired
private UserService userService2;


@Autowired
@Qualifier(value = "userService2")
private UserService userService3;

@Test
public void test(){
         System.out.println(userService1.getClass().toString());
         System.out.println(userService2.getClass().toString());
         System.out.println(userService3.getClass().toString());
}

運行結(jié)果:

class yjc.demo.serviceImpl.UserService1
class yjc.demo.serviceImpl.UserService2
class yjc.demo.serviceImpl.UserService2

運行結(jié)果成功

說明了2種處理多個實現(xiàn)類的方法:

1.變量名用userService1,userService2,而不是userService。

通常情況下@Autowired是通過byType的方法注入的,可是在多個實現(xiàn)類的時候,byType的方式不再是唯一,而需要通過byName的方式來注入,而這個name默認(rèn)就是根據(jù)變量名來的。

2.通過@Qualifier注解來指明使用哪一個實現(xiàn)類,實際上也是通過byName的方式實現(xiàn)。

由此看來,@Autowired注解到底使用byType還是byName,其實是存在一定策略的,也就是有優(yōu)先級。優(yōu)先用byType,而后是byName。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

深泽县| 余姚市| 晋宁县| 大港区| 舞阳县| 贺州市| 易门县| 康乐县| 湘乡市| 舟曲县| 武汉市| 新邵县| 陈巴尔虎旗| 富民县| 红桥区| 游戏| 洪湖市| 香河县| 双峰县| 江陵县| 南和县| 陆川县| 抚宁县| 赞皇县| 库伦旗| 平度市| 板桥市| 益阳市| 临城县| 浙江省| 商水县| 红原县| 通化县| 侯马市| 寻乌县| 若尔盖县| 贡山| 白银市| 明水县| 右玉县| 和田县|