Spring Dependency Injection

IoC的一個重點是在系統(tǒng)運行中,動態(tài)的向某個對象提供它所需要的其他對象。這一點是通過DI(Dependency Injection,依賴注入)來實現(xiàn)的。
配置文件中注入:

<bean class="cn.anlse.di.Person" id="person"> 
<!--
property:描述屬性 
name:屬性名
 ref:當我們用的是引用類型,就用ref value:
當我們用的是string類型,就用value list:當我們設置的值為list集合的話,
用list;set/map同理 --> 
<property name="list"> 
<list>
 <value>list1</value>
 <ref bean="student"/>
 <value>list3</value> </list> 
</property> 
<!-- map有點特殊,因為便利map的時候,里面都是entry,所以在設置map的值的時候,要先設置好entry --> 
<property name="map">
 <map> <entry key="m1">
 <value>map1</value>
 </entry> <entry key="m2">
 <ref bean="student"/>
 </entry> </map>
</property> 
<property name="pid" value="1"></property> 
<property name="pname" value="ansel"></property> 
<property name="set"> 
<set> <value>set1</value> 
<ref bean="student"/> 
</set> 
</property> 
<property name="student" ref="student">
</property> 
<property name="properties"> 
<props> 
<prop key="prop1"> p1 </prop> 
</props> 
</property> 
</bean> 
<bean class="cn.anlse.di.Student" id="student">
</bean>

這種在配置文件中直接賦值的方法,對于某些固定的配置文件信息比較有用。比如存放配置文件的位置及名字

利用構造函數(shù)給bean的屬性賦值

public class Person implements Serializable { 
private Long pid;
 //String 
private String pname; 
//引用類型 
private Student student;
 //集合 
private List list; 
private Set set;
 private Map map;
 //鍵值  private
 Properties properties;
 //構造函數(shù)1 
public Person(Long pid, Student student) { 
super(); this.pid = pid; this.student = student; }
 //構造函數(shù)2
 public Person(String pname, Student student) {
 this.pname = pname; this.student = student; }
//構造函數(shù)3 public Person() { } 
//構造函數(shù)4
 public Person(Long pid, String pname, Student student, List list, Set set, Map map, Properties properties) { 
this.pid = pid; this.pname = pname; this.student = student; this.list = list; this.set = set; this.map = map; this.properties = properties; } 
//省略getter&setter方法
} 

<bean class="com.xyl.constructor.Person" id="person_con"> 
<!-- constructor-argL:用來指定該bean對應的唯一構造函數(shù)的參數(shù),
因為有幾個參數(shù),就對應著有幾個參數(shù)的構造函數(shù) 
沒有這個屬性的話,默認調用空參的構造函數(shù) 
index:表示構造函數(shù)的位置,從0開始計算 type:表示該位置構造函數(shù)的類型,這里用的都是全名。
比如拿index為0的type來說,如果沒有寫type的取值,我們直接調用測試類的話 返回的pid為null。
所以也要把type寫上 ref:引用對象的名字, --> 
<constructor-arg index="0" type="java.lang.Long" value="1">
</constructor-arg> 
<constructor-arg index="1" type="cn.ansel.di.constructor.Student" ref="student_con">
</constructor-arg>
 </bean> 
<bean class="cn.ansel.di.constructor.Student" id="student_con">
</bean>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容