专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

spring的依赖注入

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容器负责对象的创建、对象之间的依赖管理等,可以降低耦合度

未经允许不得转载:搜云库技术团队 » spring的依赖注入

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们