Spring 學習筆記(一)

一、創建 bean 的四種方式

1. 調用類的默認構造方法

<bean id = "myBean" class = "com.study.spring.MyBean" />
2. 通過構造函數注入
<bean id = "myBean" class = "com.study.spring.MyBean" >
    <constructor-arg value = "myParam" />
</bean>
3. 通過構造函數注入對象的引用
<bean id = "myBean" class = "com.study.spring.MyBean" />
<bean id = "myBean2" class = "com.study.spring.MyBean2" >
    <constructor-arg ref = "myBean" />
</bean>
4. 通過工廠方法創建 bean
<bean id = "myBean" class = "com.study.spring.MyBean" factory-method = "myFactoryMethod" />


二、bean 的作用域 scope

<bean id = "myBean" class = "com.study.spring.MyBean" scope = "prototype" />


三、初始化和銷燬 bean (init-method、destory-method)

<bean id = "myBean2" class = "com.study.spring.MyBean2" 
    init-method = "method_name" destory-method = "method-name" />

    也可以爲應用上下文中所有的 bean 定義默認的初始化和銷燬方法

四、注入 bean 的屬性

1. 屬性注入(通過 setter 方法注入)

<bean id = "myBean2" class = "com.study.spring.MyBean2" >
    <property name = "simpleType" value = "simpleValue" /> <!-- 簡單屬性注入,Spring 會自動判斷和轉化簡單屬性的類型 -->
    <property name = "myBean" ref = "myBean" /> <!-- 引用其它 bean 屬性的注入 -->
    <property name = "orther">
        <bean class = "com.study.spring.other" /> <!-- 內部 bean 的注入 -->
    </property>
    <constructor-arg>
        <bean class = "com.study.spring.other" /> <!-- 也可以使用構造方法注入 -->
    </constructor-arg>
</bean>

2. 裝配集合 list、set、array 包括 <value /> <ref /> <null />

3. 裝配 map 集合

4. 裝配 properties 集合(java.util.Properties)

5. 裝配 null 值

6. 使用 Spring 命名空間 P 簡化書寫:

<bean id = "user" class = "com.study.spring.User" >
    p:userName = "goddess"
    p:otherBean-ref = "otherBean" <!-- 類型引用比簡單屬性多了 "-ref" -->
</bean>

7. 使用 SpEL 表達式裝配

<!-- 裝配簡單屬性 -->
<property name = "inttype" value = "#{23}" />
<property name = "scientific" value = "#{1e4}" />
<property name = "floatType" value = "#{11.1}" />
<property name = "stringtype" value = "#{'goddess'}" />
<property name = "booleantype" value = "#{true}" />

<!-- 引用其它 bean -->

<!-- 操作類 -->



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