Spring学习笔记 第七章 Ioc自动装载(Autowire)
IoC负责创建对象,DI负责完成对象的依赖注入,通过配置property标签的ref属性来完成,同时Spring提供了另外一种更加简便的依赖注入方式:自动装载,不需要手动配置property,IoC容器会自动选择bean完成注入。
自动装载有两种方式:
- byname:通过属性名自动装载
- byType:通过属性的数据类型自动装载
创建实体类Car.java
package com.hbb.entity;
import lombok.Data;
@Data
public class Car {
private long id;
private String name;
}
创建实体类Person.java
package com.hbb.entity;
import com.hbb.entity.Car;
import lombok.Data;
@Data
public class Person {
private long id;
private String name;
private Car car;
}
测试类PersonTest,java
package com.hbb.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hbb.entity.Person;
public class PersonTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
byName的方式如下(autowire=“byName”):
在spring.xml中配置bean
<bean id="car" class="com.hbb.entity.Car">
<property name="id" value="1"></property>
<property name="name" value="玛莎拉蒂"></property>
</bean>
<bean id="person" class="com.hbb.entity.Person" autowire="byName">
<property name="id" value="11"></property>
<property name="name" value="小红"></property>
</bean>
运行结果:
Person(id=11, name=小红, car=Car(id=1, name=玛莎拉蒂))
通过名字进行装载。将注入的事情交给IoC容器来完成。IoC容器寻找名字是car的bean,找到后,自行装载给Person。
如果找不到的话,car的值是null。(不进行装载)
byType的方式(autowire=“byType”):
在spring.xml中配置bean
<bean id="car2" class="com.hbb.entity.Car">
<property name="id" value="1"></property>
<property name="name" value="玛莎拉蒂"></property>
</bean>
<bean id="person" class="com.hbb.entity.Person" autowire="byType">
<property name="id" value="11"></property>
<property name="name" value="小红"></property>
</bean>
运行结果和byName方式相同。
byType的方式,是通过类型来进行匹配的,只要bean的类型和实体类(Person.java)中成员变量的类型(Car)是一致的,就可以进行装载。
但是使用byType会存在一个问题:如果配置文件spring.xml里同时有两个及以上的符合条件的bean时,自动装载会抛出异常(没有唯一的bean)。