251 | | |
| 251 | == bean 間的引用 == |
| 252 | |
| 253 | 在定義Bean時,除了直接指定值給屬性值之外,還可以直接參考定義檔中的其它Bean,例如HelloBean是這樣的話: |
| 254 | |
| 255 | * HelloBean.java |
| 256 | |
| 257 | {{{ |
| 258 | #!java |
| 259 | package onlyfun.caterpillar; |
| 260 | |
| 261 | import java.util.Date; |
| 262 | |
| 263 | public 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 |
| 312 | package onlyfun.caterpillar; |
| 313 | |
| 314 | import org.springframework.context.ApplicationContext; |
| 315 | import org.springframework.context.support.FileSystemXmlApplicationContext; |
| 316 | |
| 317 | public 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 | {{{ |
| 335 | Hello! It's Sat Oct 22 15:36:48 GMT+08:00 2005. |
| 336 | }}} |