属性参考

在定义Bean时,除了直接指定值给属性值之外,还可以直接参考定义档中的其它Bean,例如HelloBean是这样的话:

  • HelloBean.java
   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会帮我们完成这个依赖关系:

  • 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="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的依赖关系是否完成:

  • SpringDemo.java
   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可以改为以下:

  • 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>

执行结果与之前是相同的。