在定義Bean時,除了直接指定值給屬性值之外,還可以直接參考定義檔中的其它Bean,例如HelloBean是這樣的話:
package onlyfun.caterpillar;
import java.util.Date;
public class HelloBean { private String helloWord; private Date date; public void setHelloWord(String helloWord) { this.helloWord = helloWord; } public String getHelloWord() { return helloWord; } public void setDate(Date date) { this.date = date; } public Date getDate() { return date; } }
在以下的Bean定義檔中,先定義了一個dateBean,之後helloBean可以直接參考至dateBean,Spring會幫我們完成這個依賴關係:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="dateBean" class="java.util.Date"/> <bean id="helloBean" class="onlyfun.caterpillar.HelloBean"> <property name="helloWord"> <value>Hello!</value> </property> <property name="date"> <ref bean="dateBean"/> </property> </bean> </beans>
直接指定值或是使用<ref>直接指定參考至其它的Bean,撰寫以下的程式來測試Bean的依賴關係是否完成:
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("beans-config.xml"); HelloBean hello = (HelloBean) context.getBean("helloBean"); System.out.print(hello.getHelloWord()); System.out.print(" It's "); System.out.print(hello.getDate()); System.out.println("."); } }
執行結果如下:
Hello! It's Sat Oct 22 15:36:48 GMT+08:00 2005.
|
事實上,您也可以用內部Bean的方式來注入依賴關係,例如beans-config.xml可以改為以下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="helloBean" class="onlyfun.caterpillar.HelloBean"> <property name="helloWord"> <value>Hello!</value> </property> <property name="date"> <bean id="dateBean" class="java.util.Date"/> </property> </bean> </beans>
執行結果與之前是相同的。 |