ps:此篇接上
3.依赖注入的方式:
Spring支持3中依赖注入的方式:
—— 属性注入(最常用)
—— 构造器注入
—— 工厂方法注入(很少使用,不推荐)
(1)属性注入:
<property name="name" value="好人"></property>
value也可以作为子标签:
<property name="name">
<value>张三</value>
</property>
(2)构造器注入:
①按索引匹配入参
<bean id="student" class="com.hy.entity.Student">
<constructor-arg value="" index="0"></constructor-arg>
</bean>
index属性:表示参数的顺序(可以不写,但是顺序要一致,最好写上)
②按类型匹配入参
如果说类中不止有一个构造方法的时候,为了防止容器不知道调用哪个,可以为参数指定类型type(方法重载的区别不就是看参数的区别么)
<constructor-arg value="" type=""></constructor-arg>
4.依赖注入不同的数据类型:
(1)注入直接量(基本数据类型、字符串)
直接在value属性中书写值,若包含特殊符号,可以使用一下方式转义:
<value><![CDATA[这里写值]]></value>
(2)引用其他bean组件
①引用外部已定义好的bean:
创建Teacher类,Student类中包含Teacher的属性,配置:
<bean id="teacher" class="com.hy.entity.Teacher">
<property name="id" value="3"/>
<property name="name" value="好人"/>
</bean>
<bean id="student" class="com.hy.entity.Student">
<!-- 使用ref属性引用其他bean,也可以作为子标签使用 -->
<property name="teacher" ref="teacher" />
</bean>
②定义内部bean:
可以直接在属性中创建内部Bean,不能被外部引用
<bean id="student" class="...">
<property name="teacher">
<bean class="...Teacher">
<!-- 省略里面的配置-->
</bean>
</property>
</bean>
同样如果使用构造器注入的方式,同样使用ref属性进行引用。
(3)注入null和空字符串
①如果有时候想给实例的某些属性赋null值(当然,不赋值也是null值),这时候就可以使用到null值的特有标签<null/>
<property name="propertyName"><null/></property>
②使用<value></value>方式注入空字符串
(4)为级联属性注入值
Student类中包含Teacher类的属性,此时可以再student的bean中为teacher属性的属性赋值,这种方式很少使用,也不建议使用
<bean id="student" class="com.hy.entity.Student">
<property name="teacher" ref="teacher"></property>
<property name="teacher.name" value="好人"></property>
</bean>
注意:为teacher的属性赋值前,teacher属性一定要初始化,不然会抛异常
(5)注入集合属性
①list
假如Teacher类中包含着一个List<Student> students属性,则此时就可以使用list标签
<bean id="teacher" class="com.hy.entity.Teacher">
<property name="students">
<list>
<ref bean="student1"/>
<ref bean="student2"/>
<ref bean="student3"/>
</list>
</property>
</bean>
在list标签中可以使用<ref/>、<value/>以及内部<bean>标签
②Map
①使用entry作为map的子节点,假如在Teacher类中有一个Map<String,Student>类型的students属性
<property name="students">
<map>
<entry key="AA" value-ref="student1"></entry>
<entry key="BB" value-ref="student2"></entry>
<entry key="CC" value-ref="student3"></entry>
</map>
</property>
spring配置文件就介绍到这里辣,我们下次再见!