一、spring bean 概述
- 什麼是spring bean
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.
簡而言之:構成程序主幹結構的對象,並且由spring管理,稱之爲spring bean
二、spring 創建 bean 的三種方式
- 使用默認的構造器進行創建
<bean id="userService" class="com.lizza.service.impl.UserServiceImpl"></bean>
要求:必須要有默認構造器
- 使用普通工廠方法進行創建
<bean id="beanFactory" class="com.lizza.factory.BeanFactory"></bean>
<bean id="userDao" factory-bean="beanFactory" factory-method="getUserDao"></bean>
使用普通工廠方法創建Bean的步驟:
- 創建普通工廠對象
- 創建實例對象,需要指定普通工廠方法的實例和方法;
使用factory-bean參數指定工廠對象,使用factory-method工廠方法
- 使用靜態工廠方法進行創建
<bean id="userDao" class="com.lizza.factory.StaticBeanFactory" factory-method="getUserDao"></bean>
三、spring bean 的作用範圍
使用bean標籤的scope屬性來限定,默認是singleton,常用的是singleton和prototype
- singleton:單例模式(默認)
- prototype:多列模式
- request:作用於web應用中請求範圍
- session:作用於web應用中會話範圍
- global-session:作用於集羣環境中的會話範圍(全局session),當不是集羣環境是,它就是session
<bean id="userDao3" class="com.lizza.dao.UserDao" scope="singleton"></bean>
<bean id="userDao3" class="com.lizza.dao.UserDao" scope="prototype"></bean>
四、spring bean 的生命週期
1. 單例對象
- 創建:隨着spring容器的創建而創建(立即加載)
- 存活:只要spring容器存活,對象就存在
- 銷燬:隨着spring容器的銷燬而銷燬
- 總結:單例對象的生命週期與spirng容器的生命週期相同
2. 多例對象
- 創建:在使用對象的時候進行創建(延遲加載)
- 存活:對象在使用的時候會一直存在
- 銷燬:當對象長時間不使用,並且沒有其他對象引用的時候,會被Java的垃圾回收器回收