Spring-IoC-DI-基于xml的依赖注入-使用set方法进行注入(案例二:注入字面量属性(空值))
案例二:注入字面量属性(空值)
(1)创建类,定义属性和对应的set方法
public class Book2 {
private String bname;
private String bauthor;
public void setBname(String bname) {
this.bname = bname;
}
public void setBauthor(String bauthor) {
this.bauthor = bauthor;
}
@Override
public String toString() {
return "Book{" +
"bname='" + bname + '\'' +
", bauthor='" + bauthor + '\'' +
'}';
}
}
(2)在spring配置文件中先配置对象创建,再配置属性注入
<!-- 1.配置对象创建 -->
<bean id="book2" class="com.orz.spring.test2.Book2">
<!-- 2.属性注入 -->
<!-- 使用property完成属性注入
name:类里面的属性名称
value:向属性注入的值
-->
<property name="bname" value="降龙十八掌"></property>
<!-- 3.使用property null 注入空值 -->
<property name="bauthor">
<null></null>
</property>
</bean>
(3)测试
@Test public void test1() { //1.加载spring配置文件 ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml"); //2.获取配置文件的创建对象 Book2 book = context.getBean("book2", Book2.class); //3 System.out.println(book); }
(4)结果
Book{bname='降龙十八掌', bauthor='null'}