与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。
完整案例
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="constructor">
<property name="say" value="hello"></property>
</bean>
Student中的
package com.csdn.bean;
public class Student {
private String name;
public void setName(String name) {
this.name = name;
}
}
GreetingServiceImpl中
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;
}
public GreetingServliceImpl(Student student,Student student_1) {
this.student = student;
this.student_1=student_1;
}
private Student student;
private Student student_1;
}
值得注意的是:自动装配指的是装配bean的值而不是属性值,网上很多文章都有错误我特意的查了查资料。还有就是而该bean包含student属性(同时必须提供相应的构造方法),constructor根据构造器依赖注入的。
Autodetect讲解
bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。
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="autodetect">
<property name="say" value="hello"></property>
</bean>
Student中的文件如下
package com.csdn.bean;
public class Student {
private String name;
public void setName(String name) {
this.name = name;
}}
会自动的根据GreetingServiceImpl中是否有setStudent方法如果没有则查看是否有相应的构造方法,如果有则会根据相应的构造器注入依赖。如果有setStudent无相应的构造方法则会根据set方法注入依赖。
根据构造方法注入依赖
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;
}
public GreetingServliceImpl(Student student,Student student_1) {
this.student = student;
this.student_1=student_1;
}
private Student student;
private Student student_1;
}
Set方法注入依赖
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;
}
}