Spring3.0官網文檔學習筆記(八)--3.4.3~3.4.6

3.4.3 使用depends-on
    使用depends-on可以強制使一個或多個beans先初始化,之後再對這個bean進行初始化。

    多個bean之間用“,”、“;”、“ ”隔開。

<bean id="beanOne" class="ExampleBean" depends-on="manager"/>

<bean id="manager" class="ManagerBean" />
<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
<property name="manager" ref="manager" />
</bean>

<bean id="manager" class="ManagerBean" />
<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />
3.4.4 Lazy-initialized beans
    聲明lazy-init="true"之後,只有在第一次請求的時候纔會對bean進行初始化,不會在容器初始化的時候初始化。

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

<bean name="not.lazy" class="com.foo.AnotherBean"/>
    當然,如果一個“not lazy-initialized”bean依賴於一個“lazy-initialized”bean,那麼ApplicationContext會在啓動的時候創建“lazy-initialized”bean

<beans default-lazy-init="true">
  <!-- no beans will be pre-instantiated... -->
</beans>
3.4.5 Autowiring collaborators(自動裝配合作者)
    優點:
    1、明顯減少指定properties貨構造器屬性;
    2、當對象更新時,可以自動更新配置而不需要手動修改配置

Table 3.2. Autowiring modes

Mode Explanation
no

不自動裝配。bean的引用必須通過ref元素。

byName   

根據屬性名稱自動裝配。某個bean定義爲byName,並且它有一個叫master的屬性,那麼Spring查找定義爲master屬性的bean,然後將它注入進去

byType

如果某個bean的屬性的類型存在的話,就用這個類型的對象注入,如果存在多個,那麼拋出異常,如果沒有匹配到的話,當做沒有注入看待

constructor

與byType類似,不過是提供給構造器的參數

3.4.5.1 自動裝配的約束與缺點
    缺點:
    1、properties和constructor-arg明確的依賴設置通常會覆蓋自動裝配。不能自動裝配那些簡單的properties,如primitives,String,Classes
    2、自動裝配沒有顯示配置來的準確;

   以下暫缺

3.4.6 方法注入
    這個方法放棄了IoC。通過實現ApplicationContextAware接口,然後通過setApplicationContext方法獲取ApplicationContext,再通過getBean方法來獲取。

// a class that uses a stateful Command-style class to perform some processing
package fiona.apple;

// Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.Applicationcontext;
import org.springframework.context.ApplicationContextAware;

public class CommandManager implements ApplicationContextAware {

 private ApplicationContext applicationContext;

 public Object process(Map commandState) {
    // grab a new instance of the appropriate Command
    Command command = createCommand();
    // set the state on the (hopefully brand new) Command instance
    command.setState(commandState);
    return command.execute();
 }

 protected Command createCommand() {
    // notice the Spring API dependency!
    return this.applicationContext.getBean("command", Command.class);
 }

 public void setApplicationContext(ApplicationContext applicationContext)
                                                                  throws BeansException {
    this.applicationContext = applicationContext;
 }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章