微服务 教程
1085个小节阅读:195.8k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在之前开发中,可以通过setter方法或构造方法设置对象属性值:
xxxxxxxxxx
// setter方法设置属性
StudentService studentService = new StudentService();
StudentDao studentDao = new StudentDao();
studentService.setStudentDao(studentDao);
// 构造方法设置属性
StudentDao studentDao = new StudentDao();
StudentService studentService = new StudentService(studentDao);
Spring可以通过调用setter方法或构造方法给属性赋值
被注入类编写属性的setter方法
xxxxxxxxxx
public class StudentService {
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
配置文件中,给需要注入属性值的<bean>
中设置<property>
xxxxxxxxxx
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService">
<!--依赖注入-->
<!--name:对象的属性名 ref:容器中对象的id值-->
<property name="studentDao" ref="studentDao"></property>
</bean>
测试是否注入成功
xxxxxxxxxx
@Test
public void t2(){
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
StudentService studentService = (StudentService) ac.getBean("studentService");
System.out.println(studentService.findStudentById(1));
}