1、繼承注入
繼承注入分為兩種:普通繼承注入和抽象繼承注入
1-1、普通繼承注入
普通繼承注入,只需要在子類的bean設置parent的屬性為父類的bean就可以了
<!--父類bean--> <bean id="person" class="com.parentchild.Person" p:name="小明" p:age="15"> </bean> <!--子類:設置parent后之類會繼承父類的屬性--> <bean id="man" class="com.parentchild.Man" p:sex="男" parent="person"> </bean> <!--也可以不使用parent設置父類bean,被spring管理的子類會自動繼承父類的屬性 可以直接在子類中設置父類的屬性,如下,但是不推薦--> <bean id="man" class="com.parentchild.Man" p:sex="男" p:name="小明" p:age="115"> </bean>
1-2、抽象繼承注入
抽象父類可以是不存在的,將abstract設置為true,前提是子類需要擁有抽象父類bean中的屬性,否則注入失敗。
如果抽象父類是存在的,在父類bean中設置abstract為true就可以了。
<bean id="myperson" abstract="true"> <property name="name" value="p1"></property> <property name="age" value="2"></property> </bean>
<bean id="man2" class="com.parentchild.Man"
p:sex="男" parent="myperson">
</bean>
2、自動注入
spring自動注入的bean必須是被spring所管理的bean
自動導入不能有導入bean的id一樣的
default-autowire-candidates="*dao" 匹配所有以dao結尾的bean
default-autowire="constructor" 以構造函數匹配
default-autowire="byName" 以屬性名匹配
default-autowire="byType" 以屬性類型匹配
default-autowire="no" 無
default-autowire="default" 默認匹配
在beans中設置
default-autowire="byType" 自動匹配方式
default-autowire-candidates="*dao" 自動候選
意思是:所有的bean都會以byType的自動匹配以dao結尾bean。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byType" default-autowire-candidates="*dao"> <bean id="empdao" class="com.autowire.EmpDaoImpl"> </bean> <bean id="empservice" class="com.autowire.EmpServiceImpl"> </bean> </beans>
也可以在bean設置autowire只在此bean自動注入
<bean id="empservice" class="com.autowire.EmpServiceImpl" autowire="byType"> </bean>