> 文章列表 > Spring的IOC/DI,依赖注入的实现

Spring的IOC/DI,依赖注入的实现

Spring的IOC/DI,依赖注入的实现

Spring的IOC/DI,依赖注入的实现

https://download.csdn.net/download/weixin_41957626/87546826 资源地址

 

1.什么是Spring

1.1spring3 的体系结构图

图1 spring3的体系结构图

图2 spring4体系结构图

比较spring3的体系结构图,spring4去掉了spring3中的struts模块,添加了messaging模块和websocket模块,其他模块保持不变。spring的jar包有20个。

1.下面是spring4和5的区别?

在增强开发方面spring4是web开发增强,spring5是JDK8的增强。

在特性改进方面spring4是注解、脚本、任务、MVC等其他特性改进,spring5是测试方面的改进。

2.IOC/DI

2.1 IOC/DI

1.控制反转或者是依赖注入的含义。面向接口的编程。

2.实现方式

  • 采用工厂类的方式
  • 采用spring的ioc实现

2.2Spring的配置

1.依赖导入

<!--        spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.24</version>
        </dependency>

2.创建配置文件

<?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
id指定的是bean的名称
class指定的是bean所在的地址
ref指定的是要引入的bean
property设置的是bean的依赖的项,ref采用的是引用的数据类型的方式,value是赋一般的值的形式
-->
    <bean id="studentDao" class="cn.lxz.dao.impl.StudentDaoImpl"/>
    <bean id="studentService" class="cn.lxz.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"/>
    </bean></beans>

3.项目目录

图3 项目目录

4.实现的代码

采用的是gif的形式展示

 

图4 spring代码展示

测试类代码

    @Test
    public void testContext(){
        //采用的是读取xml的文件的配置形式
        ApplicationContext context= new ClassPathXmlApplicationContext("Spring-context.xml");
        StudentService service1=   context.getBean(StudentService.class);
        StudentService service2= (StudentService)context.getBean("studentService");
        System.out.println(service1);
        System.out.println(service2);
        service1.addStudent(new Student(1,"张三"));
    }

图5 效果图