JAVA全系列 教程
3762个小节阅读:7095.1k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替<bean>
中的依赖注入配置。
位置:属性上方、setter方法上方、构造方法上方。
注意:
@Autowired
写在属性上方进行依赖注入时,可以省略setter方法。
xxxxxxxxxx
@Component
public class StudentService {
@Autowired
private StudentDao studentDao;
public Student findStudentById(int id){
return studentDao.findById(id);
}
}
@Test
public void t2(){
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
StudentService studentService = (StudentService) ac.getBean("studentService");
System.out.println(studentService.findStudentById(1));
}
容器中没有对应类型的对象会报错
xxxxxxxxxx
// 如果StudentDaoImpl没有放到容器中会报错
//@Component("studentDao")
public class StudentDaoImpl implements StudentDao{
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"百战程序员","北京");
}
}
容器中有多个对象匹配类型时,会找beanId=属性名的对象,找不到会报错。
xxxxxxxxxx
// 如果容器中都多个同类型对象,会根据id值等于属性名找对象
@Component("studentDao")
public class StudentDaoImpl implements StudentDao{
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"百战程序员","北京");
}
}
@Component
public class StudentDaoImpl2 implements StudentDao{
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"百战程序员","北京");
}
}
1. 在Spring中,@Autowired
不能写在上方
A 属性
B setter方法
C 构造方法
D 类
答案
1=>D