Spring自动注入Bean
1.根据autowire 属性自动注入
自动注入是Spring容器根据配置文件中配置的元素,自动将依赖对象注入到调用者类中的成员变量中。要使用自动装配,就需要配置 元素的 autowire 属性。
byName:根据成员变量的 name 自动装配,如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同,则自动装配这个 Bean 到 Property 中。
byType:根据 Property 的数据类型自动装配,如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型,则自动装配。
constructor:根据构造方法的参数的数据类型,进行 byType 模式的自动装配。
autodetect:如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。被标记为过时方法,在Spring3.0之后已经不再支持。
no:默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。
1.1根据byName自动注入 (Spring配置文件总bean元素的id属性值,与调用者类中依赖对象的成员变量名称相同)
被调用者类StudentDao :
package qing.bean;
//被调用者类
public class StudentDao {
public void select() {
System.out.println("查询所学生信息!!");
}
}
调用者类StudentService :
package qing.bean;
//调用者类
public class StudentService {
//定义依赖对象
private StudentDao studentDao;
//提供set方法
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void testStudentService() {
studentDao.select();
}
}
applicationContext.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.xsd">
<!-- ByName方式注入 -->
<bean id="studentDao" class="qing.bean.StudentDao"></bean>
<bean id="studentService" class="qing.bean.StudentService" autowire="byName"></bean>
</beans>
测试类:
package qing.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService = (StudentService) ac.getBean("studentService");
studentService.testStudentService();
}
}
结果:
1.2根据byType自动注入 (Spring配置文件中bean元素的class属性值,与调用者类中依赖对象的成员变量的类型相同)
被调用者类StudentDao :
package qing.bean;
//被调用者类
public class StudentDao {
public void select() {
System.out.println("根据ByType类型 查询所学生信息!!");
}
}
调用者类StudentService :
package qing.bean;
//调用者类
public class StudentService {
//定义依赖对象
private StudentDao student;
//提供set方法
public void setStudentDao(StudentDao studentDao) {
this