Spring例項化bean的三種方法

2022-08-21 08:24:15 字數 1699 閱讀 8315

1.用構造器來例項化

<

bean

id="hello2"

class="com.hsit.hello.impl.enhello"

/>

2.使用靜態工廠方法例項化

要寫乙個bean,bean中定義乙個靜態方法,生成bean,配置factory-method指定靜態方法,執行時容器就會自動呼叫靜態方法生成例項

bean

package com.hsit.hello.impl;  

import com.hsit.hello.ihello;  

public

class chhello implements ihello   

public string getmsg()   

public

void setmsg(string msg)   

@override

public string tostring()   

public

static chhello createinstance()   

}  配置檔案

<

bean

id="hello1"

class="com.hsit.hello.impl.chhello"

factory-method="createinstance"

lazy-init="true"

>

<

property

name="msg"

value="哈哈"

>

property

>

bean

>

3.使用例項工廠方法例項化

要寫兩個bean,乙個是要例項化的bean,另乙個是工廠bean。容器先例項化工廠bean,然後呼叫工廠bean配置項factory-method中指定的方法,在方法中例項化bean

工廠bean:

package com.hsit.hello.impl;  

public

class enhellofactory   

public enhellofactory()   

}  要例項化的bean:

package com.hsit.hello.impl;  

import com.hsit.hello.ihello;  

public

class enhello implements ihello   

@override

public string tostring()   

}  配置檔案

<

bean

id="ehellofactory"

class="com.hsit.hello.impl.enhellofactory"

/>

<

bean

id="example"

factory-bean="ehellofactory"

factory-method="createinstance"

/>

測試**

enhello enhello = (enhello) factory.getbean("example");  

system.out.println(enhello.tostring());  

factory.getbean("hello1"); 

spring 三種例項化bean

利用person類的無引數建構函式例項化person類 package com.spring public class person public person string name,int age public string getname public void setname string ...

spring例項化Bean理解

技術 2009 10 17 15 56 45 閱讀127 字型大小 大 中小訂閱 有乙個bean為a,乙個bean為b。想要a在容器例項化的時候的乙個屬性name賦值為b的乙個方法funb的返回值。如果只是在a裡單純的寫著 private b b private string name b.funb...

spring例項化bean的方式

主要利用三種注入方式 介面注入 不推薦 getter,setter方式注入 比較常用 構造器注入 死的應用 關於getter和setter方式的注入 有三種匹配方式 構造器注入 2 使用靜態工廠方法例項化 利用examples.examplebean2 的靜態方法createinstance例項化乙...