【問題描述】當我們在使用Spring的IOC功能的時候,Spring提供了集中注入方式:屬性注入,構造函數注入和工廠方法注入,我們更多的時候是使用的屬性注入,即set方法注入。使用set方法注入要求我們在寫bean的配置文件的時候,需要我們手動設置properties。諸如:
- <?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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype">
- <property name="testBean" ref="testBean"/>
- </bean>
- </beans>
這樣使用Spring起來相當麻煩。
【問題分析以及解決辦法】我們在想,會不會有那種自動注入的方法呢?就是不用我們在Spring配置文件裏面寫入
- <property name="testBean" ref="testBean"/>
Spring的bean有一個autowire的屬性,它可以爲以下的6個值。
- 1、 No:即不啓用自動裝配。Autowire默認的值。
- 2、 byName:通過屬性的名字的方式查找JavaBean依賴的對象併爲其注入。比如說類Computer有個屬性printer,指定其autowire屬性爲byName後,Spring IoC容器會在配置文件中查找id/name屬性爲printer的bean,然後使用Seter方法爲其注入。
- 3、 byType:通過屬性的類型查找JavaBean依賴的對象併爲其注入。比如類Computer有個屬性printer,類型爲Printer,那麼,指定其autowire屬性爲byType後,Spring IoC容器會查找Class屬性爲Printer的bean,使用Seter方法爲其注入。
- 4、 constructor:通byType一樣,也是通過類型查找依賴對象。與byType的區別在於它不是使用Seter方法注入,而是使用構造子注入。
- 5、 autodetect:在byType和constructor之間自動的選擇注入方式。
- 6、 default:由上級標籤<beans>的default-autowire屬性確定
一般,我們在使用的時候都會用byName,這種也就是說,當我們定義bean的時候,在給bean取名的時候,約定俗成的講bean的id設置成首字母小寫的類名。在我上面的例子裏面即是testBean和testAction,這樣當我們在testAction裏面要自動注入TestBean的時候。就要在裏面寫一個Set方法,當然set方法的命名也是有規範的,那就是要set+類名,這裏即是setTestBean。
- package com.jack;
- /**
- * @author Jack Zhang
- * @version vb1.0
- * @Email [email protected]
- * @Date 2012-5-1
- */
- public class TestAction
- {
- private TestBean testBean;
- public void setTestBean(TestBean testBean)
- {
- this.testBean = testBean;
- }
- public String execute()
- {
- testBean.getCode();
- return "json";
- }
- }
- <?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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype"autowire="byName"/>
- </beans>
- <?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"
- default-autowire="byName"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype"/>
- </beans>