第一種:使用setter注入
直接使用bean元素的子元素property進行相關的設置
①簡單類型,直接使用value進行賦值。
<bean id="somebean" class="graduate.oracle.oa.domain.User" init-method="init">
<property name="id" value="123" />
</bean>
②引用類型,使用ref屬性引用另外一個bean。
<bean id="somebean" class="graduate.oracle.oa.domain.User" init-method="init">
<property name="bean" ref="otherbean"/>
</bean>
③集合類型,直接使用對應集合類型的元素即可(list,set,map,properties等)
<bean id="somebean" class="graduate.oracle.oa.dao.User" init-method="init">
<property name="list">
<!-- list代表集合 -->
<list>
<!-- value代表集合中的簡單值 -->
<value>123</value>
<value>123</value>
<!-- ref代表集合的元素是引用 -->
<ref bean="otherbean"/>
<list>
<value>innerList</value>
<value>innerList</value>
</list>
</list>
</property>
</bean>
第二中:使用構造器注入
直接使用bean元素的子元素constructor-arg
①index:在構造方法中參數的位置。
②type:參數的類型。
③value:設置對應的參數值。
<bean id ="somebean" class=""graduate.oracle.oa.dao.User">
<!-- value是參數的值 -->
<constructor- arg index="0" type="java.lang.String" value="graduate.oracle.oa.domain.User">
</constructor-arg>
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
注意:如果沒有構造方法,則使用默認的構造方法實例化對象,如果有spring則使用唯一的 constructor-arg實例化對象。