Spring自動裝配AutoWire 和 bean的生命週期

可能會用到的兩個選擇:

a) byName

b) byType

c) 如果所有的bean都用同一種,可以使用beans的屬性:default-autowire

<?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-2.5.xsd"
          >

  <bean name="userDAO1" class="com.bjsxt.dao.impl.UserDAOImpl">
  	<property name="daoId" value="1"></property>
  </bean>
  
  <bean name="userDAO2" class="com.bjsxt.dao.impl.UserDAOImpl">
  	<property name="daoId" value="2"></property>
  </bean>
	
  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType">
  </bean>
  

</beans>

如果是byName ,會返回null ,因爲userService的屬性是userDao ,但是並沒有一個name是userDao的bean

如果是byType,會報錯,因爲配置文件中 同樣類型的bean有兩個 ,刪除一個就可以

第三種 就是在文件中 以下位置 加入default-autowire="XXX"

<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-2.5.xsd"
          >

然後 bean中就可以直接寫

autowire="default"

生命週期回調

Spring提供了幾個標誌接口(marker interface),這些接口用來改變容器中bean的行爲;它們包括InitializingBeanDisposableBean。實現這兩個接口的bean在初始化和析構時容器會調用前者的afterPropertiesSet()方法,以及後者的destroy()方法。

初始化回調

實現org.springframework.beans.factory.InitializingBean接口允許容器在設置好bean的所有必要屬性後,執行初始化事宜。InitializingBean接口僅指定了一個方法:

void afterPropertiesSet() throws Exception;

通常,要避免使用InitializingBean接口並且不鼓勵使用該接口,因爲這樣會將代碼和Spring耦合起來,有一個可選的方案是,可以在Bean定義中指定一個普通的初始化方法,然後在XML配置文件中通過指定init-method屬性來完成。如下面的定義所示:

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
    
    public void init() {
        // do some initialization work
    }
}

析構回調

實現org.springframework.beans.factory.DisposableBean接口的bean允許在容器銷燬該bean的時候獲得一次回調。DisposableBean接口也只規定了一個方法:

void destroy() throws Exception;

通常,要避免使用DisposableBean標誌接口而且不鼓勵使用該接口,因爲這樣會將代碼與Spring耦合在一起,有一個可選的方案是,在bean定義中指定一個普通的析構方法,然後在XML配置文件中通過指定destroy-method屬性來完成。如下面的定義所示:

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }
}

pring容器通過配置可以實現對每個 bean初始化時的查找和銷燬時的回調調用。這也就是說,一個應用的開發者可以藉助於初始化的回調方法init() 輕鬆的寫一個類(不必想XML配置文件那樣爲每個bean都配置一個'init-method="init"'屬性)。Spring IoC容器在創建bean的時候調用這個方法 (這和之前描述的標準生命週期回調一致)。

出於示範的目的,假設一個項目的編碼規範中約定所有的初始化回調方法都被命名爲init()而析構回調方法被命名爲destroy()

<beans default-init-method="init">

    <bean id="blogService" class="com.foo.DefaultBlogService">
        <property name="blogDao" ref="blogDao" />
    </bean>

</beans>
銷燬回調方法配置是相同的 (XML配置),在頂級的<beans/>元素中使用 'default-destroy-method' 屬性。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章