Spring-IoC-DI-基於xml的依賴注入-使用set方法進行注入(案例二:注入其他型別屬性(空值))
阿新 • • 發佈:2020-08-14
案例二:注入其他型別屬性(空值)
(1)建立類,定義屬性和對應的set方法
package com.orz.spring.test2;
/**
* @author orz
* @create 2020-08-14 15:57
*/
//1.建立類
public class Book2 {
//2.定義屬性
private String bname;
private String bauthor;
//3.提供屬性的set方法
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配置檔案中先配置物件建立,再配置屬性注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 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>
</beans>
(3)測試
package com.orz.spring.test2; import com.orz.spring.test2.Book2; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author orz * @create 2020-08-14 16:01 */ public class Test1 { @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'}