Spring IOC 详解:基于 XML 配置与注解的依赖注入

news/2025/3/25 22:55:48/

Spring 框架是 Java 开发中最常用的框架之一,其核心思想之一是 IOC(Inversion of Control,控制反转)。IOC 的核心思想是将对象的创建和依赖关系的管理交给 Spring 容器来处理,从而降低代码的耦合度。本文将深入探讨 Spring IOC 的实现方式,重点讲解基于 XML 配置和基于注解的两种形式。

1. 什么是 IOC?

IOC(控制反转)是 Spring 框架的核心思想之一。传统的 Java 开发中,对象的创建和依赖关系的管理通常由开发者手动完成,这种方式会导致代码的耦合度较高。而 Spring 通过 IOC 容器来管理对象的创建和依赖关系,开发者只需要通过配置文件或注解来声明对象及其依赖关系,Spring 容器会自动完成对象的创建和依赖注入。

1.1 IOC 的优势

  • 降低耦合度:对象的创建和依赖关系由 Spring 容器管理,开发者不需要手动管理对象之间的依赖关系。

  • 提高代码的可维护性:通过配置文件或注解声明对象及其依赖关系,代码更加清晰和易于维护。

  • 便于测试:Spring 容器可以轻松地注入模拟对象,便于单元测试。

2. 基于 XML 配置的 IOC

基于 XML 配置的方式是 Spring 最早支持的 IOC 实现方式。通过在 XML 文件中配置 Bean 的定义和依赖关系,Spring 容器会根据配置文件创建对象并注入依赖。

2.1 配置 Bean

在 XML 配置文件中,使用 <bean> 标签来定义一个 Bean。每个 Bean 都有一个唯一的 id 或 name,并通过 class 属性指定 Bean 的类型。

<bean id="user" class="com.qcby.entity.User"/>

2.2 依赖注入

Spring 支持两种依赖注入方式:构造器注入 和 Setter 注入

2.2.1 构造器注入

通过构造器注入,Spring 容器会在创建对象时调用指定的构造器,并传入相应的参数。

<bean id="user" class="com.qcby.entity.User"><constructor-arg name="age" value="18"/><constructor-arg name="name" value="张三"/><constructor-arg name="animal" ref="animal"/>
</bean><bean id="animal" class="com.qcby.entity.Animal"/>
2.2.2 Setter 注入

通过 Setter 注入,Spring 容器会在创建对象后调用相应的 Setter 方法来注入依赖。

<bean id="animal" class="com.qcby.entity.Animal"><property name="strs"><array><value>张三</value><value>李四</value></array></property><property name="list"><list><value>小白</value><value>小绿</value></list></property><property name="map"><map><entry key="1" value="aa"/><entry key="2" value="bb"/></map></property>
</bean>

2.3 测试基于 XML 配置的 IOC

通过 ApplicationContext 加载 XML 配置文件,Spring 容器会自动创建并管理 Bean。

@Test
public void test1() {ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");User user = (User) ac.getBean("user");user.run();
}

3. 基于注解的 IOC

随着 Spring 的发展,基于注解的 IOC 配置方式逐渐成为主流。通过注解,开发者可以在代码中直接声明 Bean 及其依赖关系,减少了 XML 配置的复杂性。

3.1 常用注解

Spring 提供了以下常用注解来管理 Bean:

  • @Component:通用的 Bean 注解,用于标注普通的 Java 类。

  • @Controller:用于标注控制器类(通常用于 Spring MVC)。

  • @Service:用于标注服务层类。

  • @Repository:用于标注数据访问层类(DAO)。

3.2 使用注解配置 Bean

通过在类上添加 @Component 注解,Spring 容器会自动将该类注册为 Bean。

@Component(value = "user")
public class User {public void run() {System.out.println("人跑的快");}
}

3.3 依赖注入

Spring 提供了以下注解来实现依赖注入:

  • @Autowired:按类型自动注入依赖。

  • @Qualifier:与 @Autowired 配合使用,按名称注入依赖。

  • @Value:注入普通类型的值(如字符串、整数等)。

@Component(value = "animal")
public class Animal {@Value("大奔")private String name;@Autowiredprivate User user;public void flay() {System.out.println("一些动物会飞");}
}

3.4 开启注解扫描

在 XML 配置文件中,使用 <context:component-scan> 标签开启注解扫描。

<context:component-scan base-package="com.qcby.entity"/>

3.5 测试基于注解的 IOC

通过 ApplicationContext 加载配置文件,Spring 容器会自动扫描并创建注解标注的 Bean。

@Test
public void a() {ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");Animal animal = (Animal) ac.getBean("animal");animal.flay();
}

4. 总结

Spring IOC 是 Spring 框架的核心特性之一,通过控制反转和依赖注入,Spring 极大地简化了 Java 开发中的对象管理和依赖关系处理。本文详细介绍了基于 XML 配置和基于注解的两种 IOC 实现方式,并提供了相应的代码示例。

  • 基于 XML 配置的 IOC:适合传统的 Spring 项目,配置灵活但较为繁琐。

  • 基于注解的 IOC:适合现代 Spring 项目,配置简洁且易于维护。

无论是基于 XML 还是注解,Spring IOC 都能有效地降低代码的耦合度,提高代码的可维护性和可测试性。希望本文能帮助你更好地理解和使用 Spring IOC。

java">package com.qcby.entity;import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component(value = "animal")
public class Animal {private String [] strs;private List<String> list;private Map<String,String> map;@Overridepublic String toString() {return "Animal{" +"strs=" + Arrays.toString(strs) +", list=" + list +", map=" + map +'}';}public String[] getStrs() {return strs;}public void setStrs(String[] strs) {this.strs = strs;}public List<String> getList() {return list;}public void setList(List<String> list) {this.list = list;}public Map<String, String> getMap() {return map;}public void setMap(Map<String, String> map) {this.map = map;}public void flay(){System.out.println("一些动物会飞");}
}
java">import com.qcby.entity.Animal;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class ATest {@Testpublic void a(){ApplicationContext ac=new ClassPathXmlApplicationContext("Spring.xml");Animal animal=(Animal) ac.getBean("animal");animal.flay();}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!--开启注解扫描 com.qcby所有的包中的所有的类--><context:component-scan base-package="com.qcby.entity"/><!--    IOC管理bean-->
<!--    id:类的唯一标识符,class:类的全路径名-->
<!--    <bean id="user" class="com.qcby.entity.User">-->
<!--        <constructor-arg name="age" value="18"/>-->
<!--        <constructor-arg name="name" value="20"/>-->
<!--        <constructor-arg name="animal" ref="animal"/>-->
<!--    </bean>-->
<!--    <bean id="animal" class="com.qcby.entity.Animal">-->
<!--        <property name="strs">-->
<!--            <array>-->
<!--                <value>张三</value>-->
<!--                <value>李四</value>-->
<!--                <value>王五</value>-->
<!--                <value>赵六</value>-->
<!--            </array>-->
<!--        </property>-->
<!--        <property name="list">-->
<!--            <list>-->
<!--                <value>小白</value>-->
<!--                <value>小绿</value>-->
<!--                <value>小红</value>-->
<!--            </list>-->
<!--        </property>-->
<!--        <property name="map">-->
<!--            <map>-->
<!--                <entry key="1" value="aa"/>-->
<!--                <entry key="2" value="bb"/>-->
<!--                <entry key="3" value="cc"/>-->
<!--            </map>-->
<!--        </property>-->
<!--    </bean>-->
</beans>

 

 

 


参考文献:

  • Spring 官方文档

  • Spring IOC 详解

相关推荐:

  • Spring AOP 详解

  • Spring MVC 入门指南

文章来源:https://blog.csdn.net/2401_84910501/article/details/146439205
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1582429.html

相关文章

git管理时keil项目忽略文件列表

在使用 Git 管理 Keil MDK&#xff08;μVision 5&#xff09;工程时&#xff0c;需要忽略编译生成的临时文件、调试文件、用户配置等非必要内容。以下是忽略文件的详细列表及说明&#xff0c;可直接保存为 .gitignore 文件&#xff1a; Keil MDK 工程的 .gitignore 文件 giti…

Java学习总结-List的集合

List集合的特有方法: ArrayList的底层原理 第一次创建集合对象&#xff0c;size是10&#xff0c;之后扩容的时候按1.5倍扩容。 ArrayList底层基于数组存储数据的。查的的快&#xff0c;节省空间。 LinkedList底层基于链表存储数据的。增删快。

如何开发搭建交易所系统:全面指南

在数字资产日益普及的今天&#xff0c;交易所系统作为连接买家与卖家的桥梁&#xff0c;扮演着至关重要的角色。开发一个高效、安全、用户友好的交易所系统不仅是对技术的挑战&#xff0c;更是对市场理解、用户体验、合规运营等多方面能力的综合考验。本文将详细探讨如何开发搭…

Stable Diffusion lora训练(一)

一、不同维度的LoRA训练步数建议 2D风格训练 数据规模&#xff1a;建议20-50张高质量图片&#xff08;分辨率≥10241024&#xff09;&#xff0c;覆盖多角度、多表情的平面风格。步数范围&#xff1a;总步数控制在1000-2000步&#xff0c;公式为 总步数 Repeat Image Epoch …

【前端】Visual Studio Code安装配置教程:下载、汉化、常用组件、基本操作

文章目录 一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2、view-in-browser3、Live Server 四、基本操作五、感谢观看&#xff01; 一、Visual Studio Code下载 下载官网&#xff1a;https://code.visualstudio.com/ 进入官网后点击右上角的Download &…

spring boot 登入权限RBAC模式

首先准备好5张表 user_info表&#xff0c;用户的信息表 role表&#xff0c;角色表&#xff08;比如超级管理员、管理员、审核员、采购......&#xff09; 创建user_role表&#xff0c;user_info表&#xff0c;role表的中间表 注意了&#xff0c;role_id和user_id是 u…

用 pytorch 从零开始创建大语言模型(零):汇总

用 pytorch 从零开始创建大语言模型&#xff08;零&#xff09;&#xff1a;汇总 本系列官方代码库&#xff1a;https://github.com/rasbt/LLMs-from-scratch/tree/main 官方书籍&#xff1a;Build a Large Language Model (From Scratch) 本系列文章&#xff1a; 用 pytorc…

编程语言选择分析:C#、Rust、Go 与 TypeScript 编译器优化

编程语言选择分析&#xff1a;C#、Rust、Go 与 TypeScript 编译器优化 在讨论编程语言的选择时&#xff0c;特别是针对微软的 C# 和 Rust&#xff0c;以及谷歌的 Go 语言&#xff0c;以及微软试图通过 Go 来拯救 TypeScript 编译器的问题&#xff0c;我们可以从多个角度来分析和…