Changes between Version 17 and Version 18 of waue/2011/spring


Ignore:
Timestamp:
Aug 26, 2011, 4:07:03 PM (13 years ago)
Author:
waue
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • waue/2011/spring

    v17 v18  
    249249
    250250
    251 
     251 == bean 間的引用 ==
     252
     253在定義Bean時,除了直接指定值給屬性值之外,還可以直接參考定義檔中的其它Bean,例如HelloBean是這樣的話:
     254
     255 *  HelloBean.java
     256
     257{{{
     258#!java
     259package onlyfun.caterpillar;
     260
     261import java.util.Date;
     262
     263public class HelloBean {
     264    private String helloWord;
     265    private Date date;
     266   
     267    public void setHelloWord(String helloWord) {
     268        this.helloWord = helloWord;
     269    }
     270    public String getHelloWord() {
     271        return helloWord;
     272    }
     273    public void setDate(Date date) {
     274        this.date = date;
     275    }   
     276    public Date getDate() {
     277        return date;
     278    }
     279}
     280}}}
     281
     282在以下的Bean定義檔中,先定義了一個dateBean,之後helloBean可以直接參考至dateBean,Spring會幫我們完成這個依賴關係:
     283
     284 *  beans-config.xml
     285
     286{{{
     287#!xml
     288<?xml version="1.0" encoding="UTF-8"?>
     289<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
     290  "http://www.springframework.org/dtd/spring-beans.dtd">
     291
     292<beans>
     293    <bean id="dateBean" class="java.util.Date"/>
     294   
     295    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
     296        <property name="helloWord">
     297            <value>Hello!</value>
     298        </property>
     299        <property name="date">
     300            <ref bean="dateBean"/>
     301        </property>
     302    </bean>
     303</beans>
     304}}}
     305
     306直接指定值或是使用<ref>直接指定參考至其它的Bean,撰寫以下的程式來測試Bean的依賴關係是否完成:
     307
     308 *  SpringDemo.java
     309
     310{{{
     311#!java
     312package onlyfun.caterpillar;
     313
     314import org.springframework.context.ApplicationContext;
     315import org.springframework.context.support.FileSystemXmlApplicationContext;
     316
     317public class SpringDemo {
     318    public static void main(String[] args) {
     319        ApplicationContext context =
     320            new FileSystemXmlApplicationContext("beans-config.xml");
     321         
     322        HelloBean hello =
     323            (HelloBean) context.getBean("helloBean");
     324        System.out.print(hello.getHelloWord());
     325        System.out.print(" It's ");
     326        System.out.print(hello.getDate());
     327        System.out.println(".");
     328    }
     329}
     330}}}
     331
     332 * 執行結果如下:
     333
     334{{{
     335Hello! It's Sat Oct 22 15:36:48 GMT+08:00 2005.
     336}}}
    252337
    253338 = Dependency Injection =