1. 程式人生 > 其它 >[Spring]6.註解實現自動裝配

[Spring]6.註解實現自動裝配

使用註解的條件

xml的配置更改如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
		
		
    <context:annotation-config/>

</beans>

即添加了context的依賴:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
並通過<context:annotation-config/ >開啟註解

註解實現自動裝配

可以在變數名或者setter方法上新增@Autowired或者@Resource

@Autowired

預設情況下必須要求依賴物件必須存在,如果要允許null值,可以設定它的required屬性為false,如 @Autowired(required=false)。
預設使用ByType。如果上下文中有多種相同型別的bean,則會通過ByName。
通常需要搭配@Qualifier(value = "xxx")來指定bean的名稱。

@Resource

預設按照名稱進行裝配,名稱可以通過name屬性進行指定,如 @Resource(name = "xxx")
當找不到與名稱匹配的bean時才按照型別進行裝配。但是需要注意的是,如果name屬性一旦指定,就只會按照名稱進行裝配。