一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第15天,点击查看活动详情。
Bean的常用属性配置
id
bean的唯一标识,同一个Spring容器中不允许重复
class
全类名,用于反射创建对象
scope
scope主要有两个值:singleton和prototype(默认是singleton)
如果设置为singleton则一个容器中只会有这个一个bean对象。默认容器创建的时候就会创建该对象,地址。
如果设置为prototype则一个容器中会有多个该bean对象。每次调用getBean方法获取时都会创建一个新对象。
Student stu = studentDao.getStudentById(30);
Student stu2 = studentDao.getStudentById(30);
如果配置文件中
<bean class="com.sangeng.dao.impl.StudentDaoImpl" id="studentDao" scope="prototype">
prototype里面stu和stu2地址不一样,是不同的对象
<bean class="com.sangeng.dao.impl.StudentDaoImpl" id="studentDao" scope="singleton">
singleton里面stu和stu2地址一样,调用的是同一个对象
复制代码
DI依赖注入
DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。
所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。
原有方法:
//创建容器
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
Student stu = (Student) app.getBean("student");
//通过set方法
stu.setId(3);
//也可以通过构造器
Student stu2 = new Student("东南枝",20,19);
复制代码
set方法注入
在要注入属性的bean标签中进行配置。前提是该类有提供属性对应的set方法。
public class Student {
private String name;
private int id;
private int age;
private Dog dog;
复制代码
配置set方法 然后在配置文件xml中,进行属性的配置
<bean class="com.domain.Dog" id="dog">
<property name="name" value="小白"></property>
<property name="age" value="6"></property>
</bean>
<bean class="com.domain.Student" id="student" >
<!--
name属性用来指定要设置哪个属性
value属性用来设置要设置的值
ref属性用来给引用类型的属性设置值,可以写上Spring容器中bean的id
-->
<property name="name" value="东南枝"></property>
<property name="age" value="20"></property>
<property name="id" value="1"></property>
<property name="dog" ref="dog"></property>
</bean>
复制代码
注意
如果错把ref属性写成了value属性,会抛出异常:
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.atguigu.ioc.component.HappyMachine' for property 'happyMachine': no matching editors or conversion strategy found
意思是不能把String类型转换成我们要的HappyMachine类型
说明我们使用value属性时,Spring只把这个属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值