微服务 教程
1085个小节阅读:196.7k
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
自动注入不需要在<bean>
标签中添加其他标签注入属性值,而是自动从容器中找到相应的bean对象设置为属性值。
自动注入有两种配置方式:
- 全局配置:在
<beans>
中设置default-autowire
属性可以定义所有bean对象的自动注入策略。- 局部配置:在
<bean>
中设置autowire
属性可以定义当前bean对象的自动注入策略。
autowire的取值如下:
- no:不会进行自动注入。
- default:全局配置default相当于no,局部配置default表示使用全局配置
- byName:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供set方法。
- byType:在Spring容器中查找类型与属性类型相同的bean,并进行注入。需要提供set方法。
- constructor:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供构造方法。
测试自动注入:
为依赖的对象提供setter和构造方法:
xxxxxxxxxx
public class StudentService {
// 依赖
private StudentDao studentDao;
// 构造方法
public StudentService() {
}
public StudentService(StudentDao studentDao) {
this.studentDao = studentDao;
}
// setter方法
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
// 调用依赖的方法
public Student findStudentById(int id) {
return studentDao.findById(id);
}
}
配置自动注入:
xxxxxxxxxx
<!-- 根据beanId等于属性名自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byName"></bean>
xxxxxxxxxx
<!-- 根据bean类型等于属性类型自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byType"></bean>
xxxxxxxxxx
<!-- 利用构造方法自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="constructor"></bean>
xxxxxxxxxx
<!-- 配置全局自动注入 -->
<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"
default-autowire="constructor">
1. 在spring中,<bean>
中autowire
的属性值为时调用构造方法自动依赖注入
A no
B byName
C byType
D constructor
2. 在spring中,<bean>
中autowire
的属性值为时会根据属性类型自动依赖注入
A no
B byName
C byType
D constructor
1=>D 2=>C