※Setter-based注入
使用 Setter-base 時,一定要有預設建構子,否則會 runtime-exceptionBook.java
public class Book { private String bookName; private int bookMoney; private Comic comic; //setter/getter... }
Comic.java
public class Comic { private String comicName; private int comicMoney; private Book book; public String getComicName() { return comicName; } public void setComicName(String comicName) { System.out.println("comicName=" + comicName); this.comicName = comicName; } public int getComicMoney() { return comicMoney; } public void setComicMoney(int comicMoney) { System.out.println("comicMoney=" + comicMoney); this.comicMoney = comicMoney; } public Book getBook() { return book; } public void setBook(Book book) { System.out.println("book=" + book.getBookName()); this.book = book; } }
applicationContext.xml
<bean id="book" class="book.vo.Book" p:comic-ref="comic"> <property name="bookName"> <value>三國志</value> </property> <property name="bookMoney" value="620" /> </bean> <bean id="comic" class="book.vo.Comic" p:comicName="七龍珠" p:comicMoney="85" p:book-ref="book" />
測試類
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Comic comic = (Comic) ctx.getBean("comic"); System.out.println(comic.getBook().getBookName()); System.out.println(comic.getBook().getBookMoney()); ((ClassPathXmlApplicationContext) ctx).close();
※結果:
book=null
comicMoney=85
comicName=七龍珠
三國志
620
※comic的「p:」,必須在Hello World (Spring3.x 一)的標頭有Namespaces的圖,勾p的checkbox,就會在xml上方出現一些設定,這時才可以用這種寫法
※最後兩行是在測試類才run的到的程式碼,但第一次book=null,所以在啟動時是無法取得對方的內容的
※屬性第一個字與第二個字的問題
Book.java
public class Book { private String aBc; public String getaBc() { return aBc; } public void setaBc(String aBc) { this.aBc = aBc; } }
applicationContext.xml
<bean id="book" class="book.vo.Book" p:aBc="abc" />
※在網路上有人說前二個字必需全大寫或全小寫,像我這個例子就沒有,有人說啟動時spring會報錯,但我試的結果並沒有,setter/getter我都用eclipse自動產生,xml也有提示可用,我試著把第一個字改成大寫,都還是可以,可能是版本的差異吧!
※實體參照
有五個特殊字在設定XML時有可能會錯誤,可以用以下的方法取代(建構子注子和Setter-based 注入都可以這樣用)<:<
>:>
&:&
":"
':'
Book.java
public class Book { private String spcialString; // setter/getter... }
applicationContext.xml
<bean id="book1" class="book.vo.Book"> <property name="spcialString"> <value><</value> </property> </bean> <bean id="book2" class="book.vo.Book"> <property name="spcialString"> <value><![CDATA[<]]></value> </property> </bean> <bean id="book3" class="book.vo.Book"> <property name="spcialString"> <value> <![CDATA[ < ]]> </value> </property> </bean>
測試類
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Book book1 = (Book) appContext.getBean("book1"); Book book2 = (Book) appContext.getBean("book2"); Book book3 = (Book) appContext.getBean("book3"); System.out.println(book1.getSpcialString()); System.out.println(book2.getSpcialString()); System.out.println(book3.getSpcialString()); ((ClassPathXmlApplicationContext) appContext).close();
※結果:
<
<
<
※book3因為在xml設定有換行,所以也會換行,可以用trim()或者用book1或book2的方式就好了,不然真的很難看
沒有留言:
張貼留言