Spring Bean的作用域

2021-08-02 09:41:06 字數 1245 閱讀 1143

bean的作用域,常用的有兩種,單例singleton、多例prototype

預設情況下,bean都是單例的singleton。

在容器初始化的時候就被建立,就這麼乙份。

1、單例模式

例如:

測試

package com.lynn.spring.test;

import static org.junit.assert.*;

import org.junit.test;

import com.lynn.spring.dao.userdao;

import com.lynn.spring.model.user;

import com.lynn.spring.service.userservice;

import com.lynn.spring.service.impl.userserviceimpl;

public class testspring

}

結果

單例模式,即產生的是相同的物件。

2、多例模式prototype

測試

package com.lynn.spring.test;

import static org.junit.assert.*;

import org.junit.test;

import com.lynn.spring.dao.userdao;

import com.lynn.spring.model.user;

import com.lynn.spring.service.userservice;

import com.lynn.spring.service.impl.userserviceimpl;

public class testspring

}

結果:

3、設定為多例prototype時,必須是延遲載入。

單例時,可以是延遲載入或者是非延遲載入。

非延遲載入:容器初始化時建立bean

延遲載入:getbean的時候建立

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...

spring bean的作用域

一般情況下呢,我們在spring環境下配置乙個bean,這個bean是單例的。就是說ioc容器只會這個bean節點建立乙個bean物件,我們每次呼叫getbean方法都會返回同乙個bean 建立乙個car類 無參建構函式列印一句話 我出生了 public car 配置檔案 main 函式測試 car...