byType讲解

容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置dependency-check="objects"Spring抛出异常。

xml中文件的配置如下:

 

Xml文件中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	<bean id="student" class="com.csdn.bean.Student">
	<property name="name"><value>朱磊</value></property>
	</bean>
	<bean id="GreetingServliceImpl" class="com.csdn.service.GrtieengServliceImpl"
		autowire="byType">
		<property name="say" value="hello"></property>
	</bean>
</beans>


 

 

Student中为:
package com.csdn.bean;

public class Student {
	private String name;


	public void setName(String name) {
		this.name = name;
	}

}
GrtieengServliceImpl中为:
package com.csdn.service;

import com.csdn.bean.Student;

public class GreetingServliceImpl implements GreetingServlice {
	private String say;

	@Override
	public void say() {
		System.out.println("这是我说的话" + say);
	}

	public void setSay(String say) {
		this.say = say;
	}

	private Student student;

	public void setStudent(Student student) {
		this.student = student;
	}
}

 

 

值得注意的是:自动装配指的是装配bean的值而不是属性值,网上很多文章都有错误我特意的查了查资料。还有就是而该bean包含student属性(同时必须提供setStudent(..)方法),byType根据set依赖注入的。

如果xml文件中包括多个相容类型的bean利用byType会出错。(这里说的相同类型包括,如类B继承类A,如果bean中定义了类A和类B 都会出错)错误如下。

   org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '类名' defined in file

 

 

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值