Spring配置文件(二)

本文是Spring配置文件系列的第二篇,主要介绍了Spring中的依赖注入,包括属性注入、构造器注入和工厂方法注入。重点讲解了如何注入不同数据类型,如直接量、引用其他bean、null和空字符串、级联属性以及集合属性(list和map)。通过具体的例子展示了如何配置bean以满足各种注入需求。
摘要由CSDN通过智能技术生成

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配置文件就介绍到这里辣,我们下次再见!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值