1、DI概念
(1)依赖
一个对象需要另一个对象。
(2)注入
通过set方法进行另一个对象实例的设置。
如:
StudentDao studentDao=new StudentDaoImpl();
(3)DI(Dependency Injection)
DI被称为依赖注入,意思是由框架或容器将被调用类注入给调用对象,来解除调用对象和被调用对象之间的依赖关系,DI需要和IoC思想配合使用。
2、DI实例
(1)分别创建Service层和Dao层的接口和实现类:
Service层:
public interface StudentService {
public void addStudent();
}
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
public StudentServiceImpl() {
System.out.println("service的实现类被创建了!!");
}
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void addStudent(){
System.out.println("StudentService的实现类的Add方法!!");
studentDao.addStudent();
}
}
Dao层:
public interface StudentDao {
public void addStudent();
}
public class StudentDaoImpl implements StudentDao {
@Override
public void addStudent() {
System.out.println("StudentDao的实现类的Add方法!!");
}
}
(2)配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<bean id="studentDao" class="pers.zhb.dao.StudentDaoImpl">
</bean>
<bean id="studentService" class="pers.zhb.service.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
</beans>
将studentDao配置到StudentServiceImpl
(3)测试:
public class TestDi {
public static void main(String[] args) {
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("applicationContext.xml");//创建容器对象
StudentServiceImpl studentService=(StudentServiceImpl) applicationContext.getBean("studentService");
studentService.addStudent();
}
}
3、解耦
(1)以前获取dao层对象的方式:
StudentDao studentDao=new StudentDaoImpl();
(2)spring获取dao层对象的方式:
public class StudentServiceImpl {
private StudentDao studentDao;
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void addStudent(){
System.out.println("StudentService的实现类的Add方法!!");
studentDao.addStudent();
}
}
直接调用的接口,不知道实现类的具体情况。将对象的管理交给了spring容器,由spring容器负责对象的创建、对象之间的依赖管理等,可以降低耦合度