DI
就是在对象创建的同时能自动给对象中的属性赋值
看代码
get set方法赋值
- spring项目,在ApplicationContext.xml中 配置如下
<!-- 通过属性对应的set方法做自动DI-->
<!-- 通过属性对应的set方法做自动DI-->
<bean name="student" class="domain.Student">
<property name="ssex" value="男"></property>
<property name="sage" value="19"></property>
<!-- value的两种写法-->
<property name="sid">
<value>11</value>
</property>
<property name="sname">
<!-- value标签中带类型写法-->
<value type="java.lang.String">zhaoyun1</value>
</property>
</bean>
- 写一个Student实体类,有get set方法、 不带参构造方法;
- 写一个测试类
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student s = (Student) factory.getBean("student");
System.out.println(s);
}
运行结果如下
Student{sid=11, sname='zhaoyun1', ssex='男', sage=19}
构造方法赋值
- spring项目,在ApplicationContext.xml中 配置如下
<!-- 通过带参数的构造方法 给属性赋值-->
<bean name="student" class="domain.Student">
<constructor-arg name="sid" value="22" type="java.lang.Integer"></constructor-arg>
<constructor-arg name="sage" value="16" ></constructor-arg>
<constructor-arg name="sname">
<null></null>
</constructor-arg>
<constructor-arg name="ssex" value="女" type="java.lang.String"></constructor-arg>
</bean>
- 写一个Student实体类,有带参构造方法,get set方法不需要;
- 写一个测试类
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student s = (Student) factory.getBean("student");
System.out.println(s);
}
运行结果如下
Student{sid=22, sname='null', ssex='女', sage=16}
注意:使用构造方法赋值时,注意字段个数和构造方法参数要匹配,否则会有如下报错
![](https://img.haomeiwen.com/i6971875/d034c0e3acd0a54a.png)
总结
-
为什么通过配置文件就能创建对象 且能实现赋值呢,getBean方法到底做了什么?
1.读取xml文件 获取类信息Student类(配置文件有固定格式,有固定格式解析文件也就好解析了)
2.通过反射Class c = Class.forName("Student");
3.Student s = (Student)c.newInstance();
4.找class中所有私有属性Filed[] fs = c.getFields(); for(fs) 属性类型 getType 属性名字 getName 处理set方法名字 set+大写+属性名后半部分 Method m = c.getMethod(); set.invode();
//构造方法的方式
1.同上
2.同上
3.找到带参数的构造方法
Constructor con = c.getConstructor(配置决定参数个数,否则匹配不到构造方法);
配置还决定是否能与属性名匹配
反射找到属性 属性类型(所以我在配置文件中,有加类型和不加类型,表面上看加不加都行,如果不加的话底层会通过反射匹配,如果加了节省底层开销)
4.执行构造方法创建对象
con.newInstance(值);
网友评论