spring5入門(四):基於xml配置管理bean,注入特殊字元、外部bean、內部bean、級聯bean
阿新 • • 發佈:2022-04-17
- 注入null
# 方式一:可以在實體類中直接設定為空
private String oname="";
# 方式二:在bean.xml中配置如下
<property name="address">
<null/>
</property>
- 測試
# 實體類 public class Book { private String bname; private String bauthor; private String address; public void setBname(String bname) { this.bname = bname; } public void setBauthor(String bauthor) { this.bauthor = bauthor; } public void setAddress(String address) { this.address = address; } public void testDemo() { System.out.println(bname+"::"+bauthor+"::"+address); } } # bean.xml <bean id="book" class="com.ychen.spring.model.Book"> <property name="bname" value="易筋經"></property> <property name="bauthor" value="達摩老祖"></property> <property name="address"> <null/> </property> </bean> # 測試方法 @Test public void testBook1() { ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); Book book = context.getBean("book", Book.class); System.out.println(book); book.testDemo(); } # 測試 com.ychen.spring.model.Book@19932c16 易筋經::達摩老祖::null
- 注入特殊字元,直接寫在value屬性中會報錯
# 方式一:使用轉義字元,例如< >就表示 < >
# 方式二:把帶特殊符號內容寫到 CDATA
- 測試:把帶特殊符號內容寫到 CDATA
# 實體 public class Book { private String bname; private String bauthor; private String address; public void setBname(String bname) { this.bname = bname; } public void setBauthor(String bauthor) { this.bauthor = bauthor; } public void setAddress(String address) { this.address = address; } public void testDemo() { System.out.println(bname+"::"+bauthor+"::"+address); } } # bean.xml <bean id="book" class="com.ychen.spring.model.Book"> <property name="bname" value="易筋經"></property> <property name="bauthor" value="達摩老祖"></property> <property name="address"> <value><![CDATA[<<南京>>]]></value> </property> </bean> # 測試方法 @Test public void testBook1() { ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); Book book = context.getBean("book", Book.class); System.out.println(book); book.testDemo(); } # 測試 com.ychen.spring.model.Book@305ffe9e 易筋經::達摩老祖::<<南京>> Process finished with exit code 0