Changes between Version 18 and Version 19 of waue/2011/spring
- Timestamp:
- Aug 26, 2011, 4:19:35 PM (14 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
waue/2011/spring
v18 v19 251 251 == bean 間的引用 == 252 252 253 在定義Bean時,除了直接指定值給屬性值之外,還可以直接參考定義檔中的其它Bean,例如HelloBean是這樣的話: 254 255 * HelloBean.java 256 257 {{{ 258 #!java 259 package onlyfun.caterpillar; 253 * BBean.java 254 255 {{{ 256 #!java 257 package waue.org; 260 258 261 259 import java.util.Date; 262 260 263 public class HelloBean {264 private String helloWord;261 public class BBean { 262 private String baa; 265 263 private Date date; 266 264 267 public void set HelloWord(String helloWord) {268 this. helloWord = helloWord;269 } 270 public String get HelloWord() {271 return helloWord;265 public void setBaa(String ba) { 266 this.baa = ba; 267 } 268 public String getBaa() { 269 return this.baa; 272 270 } 273 271 public void setDate(Date date) { … … 275 273 } 276 274 public Date getDate() { 277 return date;278 } 279 } 280 }}} 281 282 在以下的Bean定義檔中,先定義了一個dateBean,之後 helloBean可以直接參考至dateBean,Spring會幫我們完成這個依賴關係:283 284 * beans-config.xml275 return this.date; 276 } 277 } 278 }}} 279 280 在以下的Bean定義檔中,先定義了一個dateBean,之後bBean可以直接參考至dateBean,Spring會幫我們完成這個依賴關係: 281 282 * A.xml 285 283 286 284 {{{ … … 293 291 <bean id="dateBean" class="java.util.Date"/> 294 292 295 <bean id=" helloBean" class="onlyfun.caterpillar.HelloBean">296 <property name=" helloWord">293 <bean id="bBean" class="waue.org.BBean"> 294 <property name="baa"> 297 295 <value>Hello!</value> 298 296 </property> … … 306 304 直接指定值或是使用<ref>直接指定參考至其它的Bean,撰寫以下的程式來測試Bean的依賴關係是否完成: 307 305 308 * SpringDemo.java309 310 {{{ 311 #!java 312 package onlyfun.caterpillar;306 * C.java 307 308 {{{ 309 #!java 310 package waue.org; 313 311 314 312 import org.springframework.context.ApplicationContext; 315 313 import org.springframework.context.support.FileSystemXmlApplicationContext; 316 314 317 public class SpringDemo{315 public class C { 318 316 public static void main(String[] args) { 319 317 ApplicationContext context = 320 new FileSystemXmlApplicationContext(" beans-config.xml");318 new FileSystemXmlApplicationContext("A.xml"); 321 319 322 HelloBean hello =323 ( HelloBean) context.getBean("helloBean");324 System.out.print(hello.get HelloWord());320 BBean hello = 321 (BBean) context.getBean("bBean"); 322 System.out.print(hello.getBaa()); 325 323 System.out.print(" It's "); 326 324 System.out.print(hello.getDate());