1. 程式人生 > 其它 >Spring中的Bean的作用範圍

Spring中的Bean的作用範圍

技術標籤:Spring學習筆記javaspring

Spring容器中通過Bean標籤例項化時,同時也可以指定Bean的作用範圍,通過scope=""來設定。

範圍作用描述
singletonSpring中預設的作用範圍是一個單例的模式,IOC容器中只會有一個bean定義的例項
prototype多例的,每次呼叫getBean()方法獲取bean標籤的作用範圍為prototype時,都會產生新的例項
request應用在web專案中,Spring建立這個類以後,將這個類存入到request範圍中
session應用在web專案中,Spring建立這個類以後,將這個類存入到session範圍中
globalsessio應用在web專案中,必須在porlet環境下使用。但是如果沒有這種環境,相對於session

單例模式(預設的模式):

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="singleton"></bean>

原型模式(多例的):

<bean id="userService" class="com.zy.service.impl.UserServiceImpl"
scope="prototype"></bean>

我們拿上一篇文章中的程式碼進行測試這兩種模式:
bean.xml配置bean標籤時配置為單例模式:

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="singleton"></bean>

執行測試程式碼:

public class TestDemo01 {
    public static void main(String[
] args) { //載入配置檔案 ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); //根據bean標籤的id獲取例項物件 UserService userService1 = (UserService) context.getBean("userService"); UserService userService2 = (UserService) context.getBean("userService"); //呼叫方法 userService1.saveUser(); System.out.println(userService1); System.out.println(userService2); System.out.println(userService1 == userService2); } }

執行結果:
在這裡插入圖片描述
可以看出列印兩次物件的地址都是相同的。
bean.xml配置bean標籤時配置為原型模式:

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="prototype"></bean>

繼續執行上面的測試程式碼,執行結果如下:
在這裡插入圖片描述
可以看出來列印的兩個物件的地址是不一樣的。