Spring——各种类型的自动装配

自动装配

通过约定自动赋值

原则:约定优于配置

只有对象之间的依赖关系可以自动装配(自动装配只适合与ref类型,即引用类型)

default-autowire/autowire的类型:

byName:其他bean的id值=该course类的属性名
       byType:其他bean的类型(class)是否与该course类的ref属性类型一致(注意:此种方式,必须满足:当前ioc容器中,只能有一个bean满足条件)
       constructor:其他bean的类型(class)是否与该course类的构造方法参数的类型是否一致

全局自动装配

设置全局自动装配:在配置信息后面写: default-autowire="byName"即可,之后的bean会自动找寻是否有自动装配的属性,不用单独去写每一个bean的autowire属性,但是每个bean的简单类型照常写。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
	default-autowire="byName">

<bean id="teacher" class="com.dt.entity.Teacher" >
		<property name="name" value="zs"></property>
		<property name="age" value="23"></property> 
</bean>

<bean id="course" class="com.dt.entity.Course">
		<property name="courseName" value="java"></property>
		<property name="courseHour" value="100"></property>
</bean>
</beans>

子标签装配

例如,不配置course类的teacher属性,使用自动装配找到teacher

autowire="byName"的意思:course类中,有一个引用属性,属性名为teacher,并且ioc容器中恰好配置了teacher类,且id名为teacher,就可以自动引用过来。
            即bean的id值=类的属性名

<bean id="teacher" class="com.dt.entity.Teacher" >
		
		<property name="name" value="zs"></property>
		<property name="age" value="23"></property> 
</bean>

<bean id="course" class="com.dt.entity.Course" autowire="byName">
		<property name="courseName" value="java"></property>
		<property name="courseHour" value="100"></property>
</bean>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值