1 autowire="byName"
根據名稱自動裝配,自動去IOC容器中找與屬性名同名的引用的對象,并自動注入。
<!-- ###############自動裝配############### --> <bean id="userDao" class="d_auto.UserDao"></bean> <bean id="userService" class="d_auto.UserService" autowire="byName"></bean><!-- 根據“名稱”自動裝配: userAction注入的屬性,會去ioc容器中自動查找與屬性同名的對象 --><bean id="userAction" class="d_auto.UserAction" autowire="byName"></bean>
也可以定義到全局, 這樣就不用每個bean節點都去寫autowire="byName"
<?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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byName"> 根據名稱自動裝配(全局)<!-- ###############自動裝配############### --> <bean id="userDao" class="d_auto.UserDao"></bean> <bean id="userService" class="d_auto.UserService"></bean><bean id="userAction" class="d_auto.UserAction"></bean>
</beans>
2 autowire="byType"
根據類型自動裝配:autowire="byType"必須確保改類型在IOC容器中只有一個對象;否則報錯。
<?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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byType"><!-- ###############自動裝配############### --> <bean id="userDao" class="cn.itcast.d_auto.UserDao"></bean> <bean id="userService" class="cn.itcast.d_auto.UserService"></bean><!-- 如果根據類型自動裝配: 必須確保IOC容器中只有一個該類型的對象 --><bean id="userAction" class="cn.itcast.d_auto.UserAction"></bean><!-- 報錯: 因為上面已經有一個該類型的對象,且使用了根據類型自動裝配<bean id="userService_test" class="cn.itcast.d_auto.UserService" autowire="byType"></bean>-->
</beans>
總結:
? ? Spring提供的自動裝配主要是為了簡化配置;但是不利于后期的維護。(不推薦使用)