自动注入
- 概念
在 Spring 配置文件中对象名和 ref=“id” 的id 名相同,使用自动注入,可以不配置property/ 标签 - 两种配置办法
①在bean 标签中通过 autowire=”” 配置,只对这个 bean 标签生效
②在beans 标签中通过 default-autowire=””配置,表当当前文件中所有 bean 标签都是全局配置内容
在applicationContext.xml中:
<beans
default-autowire="xxx"
>
说明:在当前配置文件中,所有类都是自动注入,注入类型是你写的xxx
代码实践
- 新建一个类Teacher
- 新建一个类People,在类中新建一个Teacher 对象,加入set和get方法
public class People{
private Teacher teacher;
public Teacher getTeacher(){
return teacher;
}
public Teacher setTeacher(Teacher teacher){
this.teacher = teacher;
}
}
- 在配置文件applicationContext.xml中
id取值任意(一般为类名首字母小写),class取包名和类名的全路径
<bean id="teacher" class="com.youdian.test.Teacher"></bean>
<bean id="people" class="com.youdian.test.People">
<property name="teacher" ref="teacher"></property>
</bean>
而用自动注入是加入了一个属性autowire
<bean id="teacher" class="com.youdian.test.Teacher"></bean>
<bean id="people" class="com.youdian.test.People" autowire=" "></bean>
可以用Test进行测试
public class Test{
public static void main(String[] args){
ApplicationContext ac=new
ClassPathXmlApplicationContext("applicationContext.xml");
People peo=ac.getBean("people",People.class);
System.out.println(peo);
}
}
注:默认没有值,可以手动设值注入
3.autowire=" " 可取值
- default: 默认值,根据全局 default-autowire=””值.默认全局和局
部都没有配置情况下,相当于 no - no: 不自动注入
- byName: 通过名称自动注入.在 Spring 容器中找类的 id
- byType: 根据类型注入
spring 容器中不可以出现两个相同类型的bean 标签 - constructor: 根据构造方法注入
①提供对应参数的构造方法(构造方法参数中包含注入对戏那个)
②底层使用 byName, 构造方法参数名和其他 bean 标签的 id相同