鏈接:https://pan.baidu.com/s/1vixLrr8harzZMwLsIB1Mwg
提取碼:ou1n
首先要明白,為什么要注入?
IOC容器會在初始化時,創建好所有的bean對象的實例(懶漢模式除外:https://www.cnblogs.com/ABKing/p/12044025.html)
這就帶來一個問題,當bean中只有方法的時候還不會出問題。
但是如果bean中還有屬性呢?
這就是屬性注入的出現原因了。為了對bean的屬性進行賦值,我們引入了注入的概念
0x00 構造器注入
配置文件中寫入:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 <bean class="top.bigking.bean.Book" id="book"> 6 <constructor-arg index="0" value="1"/> 7 <constructor-arg index="1" value="哈利波特"/> 8 <constructor-arg index="2" value="18.8"/> 9 </bean> 10 </beans>
Book類中:
1 package top.bigking.bean; 2 3 public class Book { 4 private Integer id; 5 private String bookname; 6 private double price; 7 8 public Book(Integer id, String bookname, double price) { 9 this.id = id; 10 this.bookname = bookname; 11 this.price = price; 12 } 13 14 @Override 15 public String toString() { 16 return "Book{" + 17 "id=" + id + 18 ", bookname='" + bookname + '\'' + 19 ", price=" + price + 20 '}'; 21 } 22 }
測試類中:
1 package top.bigking.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import top.bigking.bean.Book; 6 7 public class BigKingTest { 8 public static void main(String[] args) { 9 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml"); 10 Book book = (Book) applicationContext.getBean("book"); 11 System.out.println(book); 12 } 13 }
運行:
Book{id=1, bookname='哈利波特', price=18.8}
Process finished with exit code 0
可以看到,成功輸出了相應的值
這就是構造器注入
另外,還可以不通過構造器的索引,而是通過屬性名來注入
application.xml:
1 <constructor-arg name="bookname" value="哈利波特"/> 2 <constructor-arg name="id" value="1"/> 3 <constructor-arg name="price" value="18.8"/>
0x01 setter注入
這里使用的是<property>標簽,唯一的要求是,Book類中必須要有set方法,而且,由於不是構造器注入,在創建對象時,會默認調用無參的構造方法,所以在Book類中也必須要有一個無參的構造方法,否則會報錯!
1 <property name="id" value="1"/> 2 <property name="bookname" value="哈利波特" /> 3 <property name="price" value="18.8" />
占個坑,下次再寫其他的注入