2_Spring_IOC概念引入_重要

发布时间 2023-07-30 12:39:12作者: AidenDong

2_Spring_IOC概念引入_重要

image
简单的说就是,创建对象的权利,或者是控制的位置,由JAVA代码转移到spring容器,由spring的容器控制对象的创建,就是控制反转,spring创建对象时,会读取配置文件中的信息,然后使用反射给我们创建好对象之后在容器中存储起来,当我们需要某个对象时,通过id获取对象即可,不需要我们自己去new.
一句话:创建对象交给容器

Spring解耦合的原理

图解

image

创建maven项目,设置maven

先创建一个空项目

image
名字可以是spring_all

image

在项目下创建模块 名字可以是spring_test_01

image

image

pom.xml中导入spring依赖

  1.  <dependencies>
    
  2.      <dependency>
    
  3.          <groupId>org.springframework</groupId>
    
  4.          <artifactId>spring-core</artifactId>
    
  5.          <version>5.3.5</version>
    
  6.      </dependency>
    
  7.      <dependency>
    
  8.          <groupId>org.springframework</groupId>
    
  9.          <artifactId>spring-beans</artifactId>
    
  10.         <version>5.3.5</version>
    
  11.     </dependency>
    
  12.     <dependency>
    
  13.         <groupId>org.springframework</groupId>
    
  14.         <artifactId>spring-context</artifactId>
    
  15.         <version>5.3.5</version>
    
  16.     </dependency>
    
  17.     <dependency>
    
  18.         <groupId>org.springframework</groupId>
    
  19.         <artifactId>spring-expression</artifactId>
    
  20.         <version>5.3.5</version>
    
  21.     </dependency>
    
  22. </dependencies>
    

四个依赖介绍

spring-context      上下文,容器

spring-beans         创建对象

spring-core            核心jar

spring-expression 表达式jar

但是事实上,我们导入spring-context的时候,会自动导入其他依赖的jar,自动进行了依赖传递

所以,导入一个spring-context 依赖也可以

image
依赖传递关系图如下

image

为了方便测试,我们导入Junit测试依赖

  1.      <dependency>
    
  2.          <groupId>junit</groupId>
    
  3.          <artifactId>junit</artifactId>
    
  4.          <version>4.13.1</version>
    
  5.          <scope>test</scope>
    
  6.      </dependency> 
    

在项目中定义一个接口和实现类

EmpDao接口和实现类

image
接口中定义一个方法并在实现类中实现

接口

image

实现类

image

在spring配置容器中的对象

创建spring配置文件

image

文件名没有明确要求,暂时可以叫spring

image

在spring.xml中配置一个需要由容器初始化的对象

image

测试通过容器获取对象

image


Generated with Mybase Desktop 8.2.13