DI依赖注入实现方式
1.删除业务层中使用new的方式创建的dao对象
public class StudentServiceImpl implements StudentService {
//删除业务层中使用new的方式创建的dao对象
private STUdentDao studentDao;
public void student() {
studentDao.studebt();
}
}
2.在业务层提供Dao的setter方法
public class StudentServiceImpl implements StudentService {
//删除业务层中使用new的方式创建的dao对象
private StudentDao studentDao;
public void student() {
studentDao.studebt();
}
//提供对应的set方法
public void setStudentDao(StudentDao studentDao) {
this.studebtDao = studentDao;
}
}
3.在配置文件中添加依赖注入的配置
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--bean标签标示配置bean
id属性标示给bean起名字
class属性表示给bean定义类型
-->
<bean id="studentDao" class="com.test.dao.impl.StudentDaoImpl"/>
<bean id="studentService" class="com.test.service.impl.StudentServiceImpl">
<!--配置server与dao的关系-->
<!--property标签表示配置当前bean的属性
name属性表示配置哪一个具体的属性
ref属性表示参照哪一个bean
-->
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>
4.运行程序调用方法