根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为by name,而该bean包含student属性(同时提供setStudent(..)方法),Spring就会查找名为student的bean定义,并用它来装配给student属性。
Xml中的文件的配置如下:
<bean id="student" class="com.csdn.bean.Student" >
<property name="name"><value>朱磊</value></property>
</bean>
<bean id="GreetingServliceImpl" class="com.csdn.service.GreetingServliceImpl"
autowire="byName" dependency-check="all">
<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;
}
}
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(..)方法),byName根据set依赖注入的。
如果xml文件中包括多个相容类型的bean利用byName会出错。(这里说的相同类型包括,如类B继承类A,如果bean中定义了类A和类B 都会出错)错误如下。
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '类名' defined in file