之前介紹過如何在<bean>标簽中注入該bean需要使用的屬性,那麼從spring3.0以後支援注解的方式進行注入,十分便捷,隻需要在類中要注入的屬性上或者set方法上添加注解即可注入該屬性。
首先準備:導入aop的包+加限制+聲明啟動注解
包名:spring-aop-4.2.4.RELEASE.jar 因為有關注解的操作封裝在此包中
限制:加的是context的限制,可以在spring解壓的限制檔案中去找,該限制如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
開啟注解
此種注解會掃描屬性和方法上的注解--------後續的spring詳解中介紹另一種注解掃描,可以掃描類、屬性、方法上的注解
<!-- 開啟注解驅動 -->
<context:annotation-config/>
兩個注解:
@Resources
注解加在屬性上
在bean中定義要注入bean的屬性,不需要提供set方法
如果指定了name屬性,在spring容器中找到了對應的bean,就能注入,沒有找到就會報錯
@Resource不是Spring的注解,而是javax下的
注解加在set方法上
如果指定了@Resource的name如果比對不上就會報錯,不會再按類型去比對
@Autowired(配合@Qualifier)
注解加在屬性上
在bean中定義要注入bean的屬性,不需要提供set方法
注解加在set方法上
使用和加在屬性上類似
另外:@Autowired注解可以聲明(required="true")或者聲明為false。表明 此屬性bean的注入時,bean是否必須存在(被定義)。預設是true。
小結:使用注解的方式進行注入,@Resource會先比對id與屬性名或方法中的參數、方法名,若比對不到則按照接口與實作類的關系進行注入,若出現多個實作類則注入失敗。@Autowired注解的方式是直接按照接口與實作類的關系進行注入,若有多個實作類則配合@Qualifier的value值進行指定注入哪一個實作類的bean。那麼在實際開發中,無論使用哪種注解注入,最好是指定注入bean的id,增加程式的可閱讀性與可維護性
spring的再次回顧總結,若有詳述不當之處,感謝您私信糾正