容器中存在一个与指定属性类型相同的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