Book.java
public class Book { private Comic comic; public Book() {} public Book(Comic comic) { this.comic = comic; } // setter/getter... }
Comic.java
public class Comic { private String comicName; // setter/getter... }
applicationContext.xml
<!-- <bean name="ooo" class="book.vo.Comic" p:comicName="七龍珠" /> --> <!-- <bean name="book1" class="book.vo.Book" autowire="byType" /> --> <bean name="comic" class="book.vo.Comic" p:comicName="滾球王" /> <bean id="book2" class="book.vo.Book" autowire="byName" /> <bean name="xxx" class="book.vo.Comic" p:comicName="通靈王" /> <bean id="book3" class="book.vo.Book" autowire="constructor" />
測試類
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Book book = (Book) appContext.getBean("book2"); if (book.getComic() != null) { System.out.println(book.getComic().getComicName()); } ((ClassPathXmlApplicationContext) appContext).close();
※我試的結果byType和另外其中一種混用,就會出「org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [book.vo.Comic] is defined: expected single matching bean but found 2: ooo,comic」的錯
因為byType是根據型態,只要是class裡的field有的型態都會去抓,沒抓到不會報錯,只是null而已,但抓到2個以上就會報錯,因為它不知道要抓哪個
※byName是根據名稱,只要是class裡的名稱和xml的name、id、alias一樣就會去抓,沒抓到不會報錯,只是null而已
不用擔心name和id名稱都一樣的問題,run起來console就會說不能重覆了
※constructor是根據建構子的型態,一定要剛好是一個,沒有或超過都會報錯
我試的結果不管byName寫在constructor上面或下面,都會被byName覆蓋,
沒有留言:
張貼留言