
正文
Bean的构造器注入和setter注入
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
链接:https://pan.baidu.com/s/1vixLrr8harzZMwLsIB1Mwg
提取码:ou1n
首先要明白,为什么要注入?
IOC容器会在初始化时,创建好所有的bean对象的实例(懒汉模式除外:https://www.cnblogs.com/ABKing/p/12044025.html)
这就带来一个问题,当bean中只有方法的时候还不会出问题。
但是如果bean中还有属性呢?
这就是属性注入的出现原因了。为了对bean的属性进行赋值,我们引入了注入的概念
0x00 构造器注入
配置文件中写入:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="top.bigking.bean.Book" id="book">
<constructor-arg index="0" value="1"/>
<constructor-arg index="1" value="哈利波特"/>
<constructor-arg index="2" value="18.8"/>
</bean>
</beans>
Book类中:
package top.bigking.bean;
public class Book {
private Integer id;
private String bookname;
private double price;
public Book(Integer id, String bookname, double price) {
this.id = id;
this.bookname = bookname;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", bookname='" + bookname + '\'' +
", price=" + price +
'}';
}
}
测试类中:
package top.bigking.test; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.bigking.bean.Book; public class BigKingTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
Book book = (Book) applicationContext.getBean("book");
System.out.println(book);
}
}
运行:
Book{id=1, bookname='哈利波特', price=18.8}
Process finished with exit code 0
可以看到,成功输出了相应的值
这就是构造器注入
另外,还可以不通过构造器的索引,而是通过属性名来注入
application.xml:
<constructor-arg name="bookname" value="哈利波特"/>
<constructor-arg name="id" value="1"/>
<constructor-arg name="price" value="18.8"/>
0x01 setter注入
这里使用的是<property>标签,唯一的要求是,Book类中必须要有set方法,而且,由于不是构造器注入,在创建对象时,会默认调用无参的构造方法,所以在Book类中也必须要有一个无参的构造方法,否则会报错!
<property name="id" value="1"/>
<property name="bookname" value="哈利波特" />
<property name="price" value="18.8" />
占个坑,下次再写其他的注入






