聊聊@Autowired注解注入,寫接口名字還是實現(xiàn)類的名字
用@Autowired注解注入,寫接口名字還是實現(xiàn)類的名字
來自某程序員一個問答問題
1. 有一點沒明白,為什么注解@repository注解的是接口UserDAO的實現(xiàn)類UserDAOImpl,而在UserServiceImpl中使用@Autowired注解注入屬性private UserDAO userDAO自動裝配,為什么最后得到的是UserDAOImpl的實例。
-----上面是某位同學的提問,我也有這樣的疑問----
2. @Service注解服務層的時候,在unitest中,是從ApplicationContext.getBean("實現(xiàn)類名字,首字母小寫") 這樣獲取的。
也就是說,在容器中初始化的Bean應該按照實現(xiàn)類名字規(guī)則。 這一點如果是用xml配置是不存在這樣的問題,因為xml可以指定id, id 是接口,class指向實現(xiàn)類。
3. 來自網(wǎng)友的回答:這個其實是創(chuàng)建了實現(xiàn)類的對象但引用了接口類型,即"InjectionDao injectionDao = new InjectionDaoImpl()", 這個其實是Java多態(tài)性(向上轉型)的一種應用。在實現(xiàn)類處加@Repository注解,意思就是new InjectionDaoImpl(), 而在InjectionServiceImpl中定義屬性InjectionDAO injectionDAO就是將new出來的這個InjectionDaoImpl對象向上轉型為InjectionDao類型。
Spring中Autowired注入接口的幾個問題
1.Spring怎么知道注入哪個實現(xiàn)?
As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair.
If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
如果Spring配置了component scan,并且要注入的接口只有一個實現(xiàn)的話,那么spring框架可以自動將interface于實現(xiàn)組裝起來。如果沒有配置component scan,那么你必須在application-config.xml(或等同的配置文件)定義這個bean。
可以理解為 在 application-service.xml 配置文件中聲明了 component-scan
<context:component-scan base-package="com.system.service.impl"/>
在 com.system.service 下有一個接口類,在 com.system.service.impl 下有一個接口對應的實現(xiàn)類,且該實現(xiàn)類用 @Service 注解進行了標注。
在使用該接口類的時候,可以按照如下方式:
@Autowired private UserloginService userloginService;
以此來進行自動裝配。
2.需要@Qualifier和@Resource注解嗎?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation.
If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.
一旦一個接口有多個實現(xiàn),那么就需要每個特殊化識別并且在自動裝載過程中使用@Qualifier和@Autowired一起使用來標明。如果是使用@Resource注解,那么你應該使用resource中屬性名稱來標注@Autowired.
3.為什么@Autowired使用在interface上而不是實現(xiàn)類上?
Firstly, it is always a good practice to code to interfaces in general.
Secondly, in case of spring, you can inject any implementation at runtime.
A typical use case is to inject mock implementation during testing stage.
首先,一般使用接口是很常用并且有益的變成技術。
其次,在spring中,你可以在運行過程中注入各種實現(xiàn)。一個很經(jīng)典的情況就是在測試階段,注入模擬的實現(xiàn)類。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringSecurity中@PermitAll與@PreAuthorize的實現(xiàn)
@PermitAll和@PreAuthorize都是處理安全性的強大工具,本文主要介紹了SpringSecurity中@PermitAll與@PreAuthorize的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-07-07
SpringMVC+Mybatis實現(xiàn)的Mysql分頁數(shù)據(jù)查詢的示例
本篇文章主要介紹了SpringMVC+Mybatis實現(xiàn)的Mysql分頁數(shù)據(jù)查詢的示例,具有一定的參考價值,有興趣的可以了解一下2017-08-08
java對象序列化與反序列化的默認格式和json格式使用示例
這篇文章主要介紹了java對象序列化與反序列化的默認格式和json格式使用示例,需要的朋友可以參考下2014-02-02

