SSM-Spring-06:Spring的自动注入autowire的byName和byType
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
di的注入上次讲了一些,这次主要阐述域属性的自动注入
先讲byType方式
看名字就知道是根据类型进行自动注入
案例:
实体类:(俩个,一个学生类,一个汽车类)
package cn.dawn.day06autowire; /** * Created by Dawn on 2018/3/5. */ //student类 public class Student { private String name; private Integer age; private Car car; //带参构造 public Student(String name, Integer age, Car car) { this.name = name; this.age = age; this.car = car; } //无参构造 public Student() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } } package cn.dawn.day06autowire; /** * Created by Dawn on 2018/3/5. */ public class Car { private String color; private String type; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
在配置文件中:
<!--汽车的bean--> <bean id="car" class="cn.dawn.day06autowire.Car"> <property name="color" value="黑色"></property> <property name="type" value="奥迪"></property> </bean> <!--装配student--> <bean id="student" class="cn.dawn.day06autowire.Student" autowire="byType"> <property name="name" value="马云"></property> <property name="age" value="18"></property> </bean>
单测方法:
package cn.dawn.day06autowire; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by Dawn on 2018/3/3. */ public class test20180306 { @Test /*di自动注入*/ public void t01(){ ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day06autowire.xml"); Student student = (Student) context.getBean("student"); System.out.println("学生"+student.getName()+"开着"+student.getCar().getColor()+"的"+student.getCar().getType()); } }
单测后可以正常执行
但是问题来了:如果有一个类继承Car,并且在spring的配置文件中配置了他的bean,那么byType还可以吗?
结果是不行的,它报错的解释是,不能自动装配,有比一个多的car类型,所以,引出了另外一种方式byName
-------------------------------------------------------------------------------------------------------------
byName的方式,要求实体类的关联的那个对象名要和上面配置的bean的id一样,就可以自动装配,我的上面汽车的bean的id是car,说明只要Student类中的关联的Car类型的对象的名字是car就可以自动装配
代码
<bean id="student" class="cn.dawn.day06autowire.Student" autowire="byName"> <property name="name" value="马云"></property> <property name="age" value="18"></property> </bean>
结果依旧,正常运行