链接: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" />
占个坑,下次再写其他的注入
来源:https://www.cnblogs.com/ABKing/p/12044663.html