快速上手Spring--7. ref的用法 |
發佈時間:2006.03.17 09:51 來源:csdn 作者:javamxj |
這篇文章來談談《Spring Framework 開發參考手冊》的3.3.2小節中的ref的用法。
ref元素是用在property中,來設置需要引用的容器管理的其它Bean。
它的用法:,這裏主要分析一下這三個參數的作用。
這次先看實例,再進行講解。
· 先建立一個包:javamxj.spring.basic.ref ,然後把以下5個文件放在這個包下。
beans.xml xml version="1.0" encoding="GBK"?>
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="helloBean"class="javamxj.spring.basic.ref.HelloBean"> <property name="hello" value="Hello! Child Bean." /> bean> <bean id="dateBean" name="#date"class="java.util.Date"/> <bean id="hd1"class="javamxj.spring.basic.ref.HelloDate"> <property name="hb"> <ref bean="helloBeanParent"/> property> <property name="date"> <ref bean="#date"/> property> bean> <bean id="hd2"class="javamxj.spring.basic.ref.HelloDate"> <property name="hb"> <ref local="helloBean"/> property> <property name="date"> <ref local="dateBean"/> property> bean> <bean id="hd3"class="javamxj.spring.basic.ref.HelloDate"> <property name="hb"> <ref parent="helloBean"/> property> <property name="date"> <bean class="java.util.Date"/> property> bean> beans>
·運行Main.java,輸出結果如下:
Hello! Parent Bean. 2005-8-10 22:25:56
Hello! Child Bean. 2005-8-10 22:25:56 Hello! Javamxj. 2005-8-10 22:25:56 OK!這裏主要分析beans.xml、Main.java這兩個文件。對於Main.java要注意的是如何加載“parent”的,重點看看beans.xml中ref元素的用法。
首先定義兩個bean:helloBean、dateBean,分別指向HelloBean類和Date類。然後定義了hd1、hd2、hd3等三個bean,都指向HelloDate類。
·hd1:
property標籤中的“helloBeanParent”並不存在於beans.xml中,而是在parent.xml中,使用可以從其它bean配置文件中尋找需要加載的目標bean。bean屬性的值可以同目標bean的id屬性相同,也可以同它的name屬性中任意的一個值相同。
·hd2:
property標籤中的“helloBean”如果不存在於beans.xml中,則XML解析器會提示錯誤。只能這個bean配置文件中尋找需要加載的目標bean,而且local屬性值必須同目標bean的id屬性相同。
·hd3:
property標籤中的“helloBean”同時存在於beans.xml和parent.xml中,使用則會優先從beans.xml中尋找需要加載的目標bean,如果需要從parent.xml中加載目標bean,則需使用。在設置date時,使用的是內聯bean,這時可以不要任何id或name定義。
好了,就說這麼多了。
|