Spring框架中bean配置
阿新 • • 發佈:2018-12-19
Spring IOC 基於xml開發
bean的配置
*<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.xsd">* 此處如果用的是idea,直接在resources目錄下new中選擇 XML Configuration File下 Spring Config即可自動生成
**
spring對bean的管理細節
** 1.建立bean的三種方式 2.bean物件的作用範圍 3.bean物件的生命週期
配置service
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
1.1關於配置service
<!-- 第一種方式:使用預設建構函式建立。 在spring的配置檔案中使用bean標籤,配以id和class屬性之後,且沒有其他屬性和標籤時。 採用的就是預設建構函式建立bean物件,此時如果類中沒有預設建構函式,則物件無法建立。 <bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl"></bean> --> <!-- 第二種方式: 使用普通工廠中的方法建立物件(使用某個類中的方法建立物件,並存入spring容器) <bean id="instanceFactory" class="com.xxx.factory.InstanceFactory"></bean> <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean> --> <!-- 第三種方式:使用工廠中的靜態方法建立物件(使用某個類中的靜態方法建立物件,並存入spring容器) <bean id="accountService" class="com.xxx.factory.StaticFactory" factory-method="getAccountService"></bean> -->
1.2bean的作用範圍調整
bean標籤的scope屬性: 作用:用於指定bean的作用範圍 取值: 常用的就是單例的和多例的 singleton:單例的(預設值) prototype:多例的 request:作用於web應用的請求範圍 session:作用於web應用的會話範圍 global-session:作用於叢集環境的會話範圍(全域性會話範圍),當不是叢集環境時,它就是session <bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl" scope="prototype"></bean>
1.3bean的生命週期
單例物件
出生:當容器建立時物件出生
活著:只要容器還在,物件一直活著
死亡:容器銷燬,物件消亡
總結:單例物件的生命週期和容器相同
多例物件
出生:當我們使用物件時spring框架為我們建立
活著:物件只要是在使用過程中就一直活著。
死亡:當物件長時間不用,且沒有別的物件引用時,由Java的垃圾回收器回收
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl"
scope="prototype" init-method="init" destroy-method="destroy"></bean>