筆記 Spring的Bean例項的作用域

2021-09-12 23:39:35 字數 2462 閱讀 5543

**測試

在spring中,可以在元素的屬性中設定bean的作用域,以決定這個bean是單例的還是多例項的

預設情況下,spring只為每個在ioc容器裡生命的bean建立唯一乙個例項,整個ioc容器範圍內都能共享該例項:所有後續的getbean()呼叫和bean引用都將返回這個唯一bean例項。該作用於被稱為singleton,它是所有bean的預設作用域

類別說明

singleton

在springioc容器中僅存在乙個bean例項,bean以單例項的方式存在

prototype

每次呼叫getbean()時都會返回乙個新的例項

當bean的作用域為單例時,spring會在ioc容器物件建立時就建立bean的物件例項

public

class

book

public

book

(integer id, string title, string author,

double price, integer sales)

public

book

(integer id, string title, string author,

double price)

public

book

(integer id, string title, string author, integer sales)

public integer getid()

public

void

setid

(integer id)

public string gettitle()

public

void

settitle

(string title)

public string getauthor()

public

void

setauthor

(string author)

public

double

getprice()

public

void

setprice

(double price)

public integer getsales()

public

void

setsales

(integer sales)

@override

public string tostring()

}

class

springtest

}

更改beans.xml中的配置

"book"

class

="com.atguigu.spring.beans.book"

scope

="singleton"

>

name

="id"

value

="8"

>

property

>

name

="title"

value

="紅高粱"

>

property

>

name

="author"

value

="莫言"

>

property

>

name

="price"

value

="10.00"

>

property

>

name

="sales"

value

="800"

>

property

>

bean

>

singleton 時 ,執行結果如下: 只建立一次bean

prototype:執行結構如下

"book"

class

="com.atguigu.spring.beans.book"

scope

="prototype"

>

...bean

>

每次例項化都會建立乙個新的book物件

spring學習筆記(bean的例項化)

spring中bean的例項化 spring中是通過ioc容器來管理bean的,那麼spring中如何初始化呢?spring中有三種例項化的方式 首先建立乙個class bean.2.在spring配置檔案中配置 3.測試類中例項化bean 1.新建乙個工廠類beanfactory,編寫乙個靜態方法...

Spring內部bean例項

使用情形 在spring框架中,bean a只作為另外乙個bean b的屬性,那麼可以把a作為b的內部bean例項。內部bean例項支援setter注入和構造器注入。cat物件是animaser物件的乙個內部bean例項 animaser類 public class animalser public...

Spring內部bean例項

在spring框架中,乙個bean僅用於乙個特定的屬性,這是提醒其宣告為乙個內部bean。內部bean支援setter注入 property 和構造器注入 constructor arg 下面來看看乙個詳細的例子,演示使用 spring 內部 bean package com.yiibai.comm...