Spring Bean的作用域(作用範圍)

2021-10-14 18:41:58 字數 2003 閱讀 8488

文章目錄

scope

1. 註解方式配置

1.1 測試singleton

1.2 測試prototype

2. xml方式配置

在spring中使用 scope來表示乙個bean定義對應產生例項的型別,也可以說是對應例項的作用範圍。spring中 指定scope的方法分以下兩種:

採用xml配置方式時,可以用標籤中的scope屬性可以指定bean的作用範圍。

採用註解方式時,可以用@scope(value = "singleton")來指定

scope

scope有如下五個取值:

singleton:單例的(預設的),使用singleton定義的bean是單例的,每次呼叫getbean都是呼叫的同乙個物件。只要ioc容器一建立就會建立bean的例項。

prototype:多例的,每次通過spring ioc容器獲取prototype定義的bean時,容器都將建立乙個新的bean例項。建立時不會例項該bean,只有呼叫getbean方法時,才會例項化。

request:作用於web的請求範圍,在每一次http請求時,容器會返回bean的同乙個例項,對不同的http請求則會產生乙個新的bean,而且該bean僅在當前http request內有效。

session:作用於web的會話範圍,在一次http session中,容器會返回該bean的同乙個例項,對不同的http請求則會產生乙個新的bean,而且該bean僅在當前http session內有效。

global-session:作用於集群環境的會話範圍(全域性會話範圍),在乙個全域性的http session中,容器返回bean的同乙個例項。當不是集群環境時,它就是session。

配置方式如下有如下兩種:

註解方式配置

註解方式配置時,只需在需要配置的bean上使用@scope註解即可,如下:

1.1 測試singleton

@component(value = 「accountservice」)//預設名稱是accountserviceimpl

//@scope(value = 「singleton」) 此處預設是singleton

public class accountserviceimpl implements accountservice

}//3.列印獲取的物件

system.out.println(accountservice);

system.out.println(accountservice2);

system.out.println(accountservice == accountservice2);

}執行結果:

com.xingze.service.impl.accountserviceimpl@dbd940d

com.xingze.service.impl.accountserviceimpl@dbd940d

true

1.2 測試prototype

**中增加`@scope(value = 「prototype」),如下:

@component(value = 「accountservice」)//預設名稱是accountserviceimpl

@scope(value = 「prototype」)

public class accountserviceimpl implements accountservice

}執行結果:

com.xingze.service.impl.accountserviceimpl@2df32bf7

com.xingze.service.impl.accountserviceimpl@530612ba

false

分析:spring bean的預設作用範圍scope是singleton的,而prototype是多例的。

2. xml方式配置

xml方式配置作用域只需在spring配置檔案中配置bean時加入scope屬性即可。如下:

Spring Bean的作用域

bean的作用域,常用的有兩種,單例singleton 多例prototype 預設情況下,bean都是單例的singleton。在容器初始化的時候就被建立,就這麼乙份。1 單例模式 例如 測試 package com.lynn.spring.test import static org.junit...

Spring bean的作用域

spring框架中,bean 的作用域有如下五種 1.單例 每個spring的ioc容器返回來乙個bean例項 框架預設 2.原型 當每次請求時候都返回來乙個bean例項 3.請求 每個http請求返回來乙個bean例項 4.會話 每個http會話返回來乙個bean例項 5.全域性會話 返回全域性會...

Spring Bean的作用域

在xml檔案中配置bean時,我們可以通過scope為bean配置指定的作用域。bean的作用域分為五種 說明 singleton 單例模式,乙個bean容器中只存在乙個bean例項 prototype 原型模式,每次請求都會產生乙個新的bean例項 request 每次http請求會產生乙個新的b...