通过bean标签的Autowire属性实现byName自动装配和byType自动装配
自动装配方法
public class Emp {
private Dept dept;
//这个set方法必须写,不能使用有参构造器完成自动装配
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
'}';
}
}
<bean id="emp" class="com.carl.autowire.Emp" autowire="byName">
<!-- <property name="dept" ref="dept"/>-->
</bean>
<bean id="dept" class="com.carl.autowire.Dept"/>
说明:
byName和byType的区别
byName:
- 根据属性名称注入,属性名称必须和注入的bean的id一样,如果找不到,默认为null
byType:
- 根据属性类型注入,属性的类型必须和注入的bean的class一样,如果找不到就会报错
Could not autowire. There is more than one bean of 'Dept' type. Beans: dept1,dept. Properties: 'dept'