Spring中的IOC

news2025/2/24 23:55:01

IOC(Inversion of Control,控制反转)是Spring框架核心概念之一。它是一种设计原则,用来实现对象的松耦合和依赖管理。在传统的编程中,对象负责创建或查找其依赖对象,而在IOC模式下,这些职责被移交给一个容器,由容器来负责对象的创建和管理。

本文章将介绍几种实现IOC的方式

目录

一.前提准备

二.基于xml的方式

三.基于注解的方式

四.基于配置类的方式


一.前提准备

1)引入Spring的相关依赖:

2)创建示例类(要交给Spring管理的类):

@Data
public class DataConfig {
   
    private String url;
    
    private String driverName;
    
    private String userName;
   
    private String password;

}

注意:@Data注解是由Lombok提供的

Lombok 是一个用于 Java 编程的开源库,旨在通过自动生成常见代码来简化开发过程。其主要功能是减少样板代码(boilerplate code),如 getter、setter、构造函数、equals 和 hashCode 方法等,从而使代码更加简洁和易于维护。 

二.基于xml的方式

首先在src/main/resources目录下创建xml文件,文件名可自定义,但是后缀为.xml

将xml文件用来定义Bean时为固定格式,示例如下:

<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       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">

    <!-- 配置 User 对象 -->
    <bean class="com.example.spring_demo.ioc.DataConfig" id="config">
        //里面写要定义的属性
        //id用来给要管理的对象取名
    </bean>

</beans>

我们将要配置的属性写进去:

<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       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">

    <!-- 配置 User 对象 -->
    <bean class="com.example.spring_demo.ioc.DataConfig" id="config">
        <property name="driverName" value="Driver"></property>
        <property name="url" value="localhost:8080"></property>
        <property name="userName" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

</beans>

最后通过IOC容器ApplicationContext来管理和获取Bean。

public class Test {
    public static void main(String[] args) {

        ApplicationContext context1=new ClassPathXmlApplicationContext("springIoc.xml");

        System.out.println(context1.getBean("config"));
        
    }
}

结果如下:

23:35:58.074 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1c655221
23:35:58.201 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [springIoc.xml]
23:35:58.228 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config'

DataConfig(url=localhost:8080, driverName=Driver, userName=root, password=root)

Process finished with exit code 0

三.基于注解的方式

使用注解的方式相对简单,只需要给目标类添加 @Component 即可

@Data
@Component("config2")
public class DataConfig {
    @Value("localhost:3306")
    private String url;
    @Value("Driver")
    private String driverName;
    @Value("root")
    private String userName;
    @Value("root")
    private String password;
}

//@Component注解告知Spring这个类交给ioc容器管理

//"config"是给要管理的对象取的名字

//@Value给管理的对象注入初始值

接着通过IOC容器ApplicationContext来管理和获取Bean

public class Test {
    public static void main(String[] args) {

        ApplicationContext context3=new AnnotationConfigApplicationContext("com.example.spring_demo.ioc");

        System.out.println(context3.getBean("config2"));
    }
}

//"com.example.spring_demo.ioc"是要扫描的类所在的包,Spring会查找该包有无要管理的类

结果如下:

23:44:44.345 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@53e25b76
23:44:44.362 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
23:44:44.448 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
23:44:44.450 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
23:44:44.451 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
23:44:44.452 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
23:44:44.458 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanConfiguration'
23:44:44.462 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config1'
23:44:44.469 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config2'

DataConfig(url=localhost:3306, driverName=Driver, userName=root, password=root)

四.基于配置类的方式

这种方式和xml的原理一样,只不过是使用java代码的形式来实现的,它定义了一个的专门的配置类来存放我们要管理的类,配置类要加上@Configuration注解

首先创建配置类

@Configuration
public class BeanConfiguration {

    //默认id是方法名,id可使用name属性来配置
    @Bean(name="config2")
    public DataConfig dataConfig(){
        DataConfig dataConfig=new DataConfig();
        dataConfig.setDriverName("Driver");
        dataConfig.setUrl("localhost:3306/spring_demo");
        dataConfig.setUserName("root");
        dataConfig.setPassword("root");
        return dataConfig;
    }
}

接着通过IOC容器ApplicationContext来管理和获取Bean

public class Test {
    public static void main(String[] args) {

       ApplicationContext context2=new AnnotationConfigApplicationContext("com.example.spring_demo.ioc");

        System.out.println(context2.getBean("config1"));

       
    }
}

结果如下:

23:56:29.299 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [D:\code\blog_code\target\classes\com\example\spring_demo\ioc\BeanConfiguration.class]
23:56:29.301 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [D:\code\blog_code\target\classes\com\example\spring_demo\ioc\DataConfig.class]
23:56:29.313 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@53e25b76
23:56:29.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
23:56:29.413 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
23:56:29.415 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
23:56:29.416 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
23:56:29.417 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
23:56:29.423 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beanConfiguration'
23:56:29.428 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config1'
23:56:29.435 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config2'

DataConfig(url=localhost:3306, driverName=Driver, userName=root, password=root)

Process finished with exit code 0

到这里关于SpringIOC实现的三种方式就介绍完了~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1820873.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++ | Leetcode C++题解之第150题逆波兰表达式求值

题目&#xff1a; 题解&#xff1a; class Solution { public:int evalRPN(vector<string>& tokens) {int n tokens.size();vector<int> stk((n 1) / 2);int index -1;for (int i 0; i < n; i) {string& token tokens[i];if (token.length() >…

24年大一尺取练习(东北林业大学)

前言&#xff1a; 今天下午才刚看到oj上发了这次练习&#xff0c;我已经错过了截止时间&#xff0c;刚好不是很想复习六级&#xff0c;就把这次练习补了吧。 正文&#xff1a; Problem:A 尺取Language&#xff1a; #include<bits/stdc.h> using namespace std; const i…

如何把路由器设备的LAN口地址为三大私网地址

要将路由器的LAN口地址配置为三大私有IP地址范围之一&#xff08;10.0.0.0/8、172.16.0.0/12 或 192.168.0.0/16&#xff09;&#xff0c;我们需要访问路由器的管理界面并进行相应的设置。 下面是步骤&#xff1a; 连接到路由器&#xff1a; 连接到路由器的管理界面&#xf…

C++设计模式——Bridge桥接模式

一&#xff0c;桥接模式简介 桥接模式是一种结构型设计模式&#xff0c;用于将抽象与实现分离&#xff0c;这里的"抽象"和"实现"都有可能是接口函数或者类。 桥接模式让抽象与实现之间解耦合&#xff0c;使得开发者可以更关注于实现部分&#xff0c;调用…

谷粒商城实战(036 k8s集群学习2-集群的安装)

Java项目《谷粒商城》架构师级Java项目实战&#xff0c;对标阿里P6-P7&#xff0c;全网最强 总时长 104:45:00 共408P 此文章包含第343p-第p345的内容 k8s 集群安装 kubectl --》命令行操作 要进入服务器 而且对一些不懂代码的产品经理和运维人员不太友好 所以我们使用可视化…

【5.x】ELK日志分析

ELK日志分析 一、ELK概述 1、ELK简介 ELK平台是一套完整的日志集中处理解决方案&#xff0c;将ElasticSearch、Logstash和Kiabana三个开源工具配合使用&#xff0c;完成更强大的用户对日志的查询、排序、统计需求。 一个完整的集中式日志系统&#xff0c;需要包含以下几个主…

Java | Leetcode Java题解之第149题直线上最多的点数

题目&#xff1a; 题解&#xff1a; class Solution {public int maxPoints(int[][] points) {int n points.length;if (n < 2) {return n;}int ret 0;for (int i 0; i < n; i) {if (ret > n - i || ret > n / 2) {break;}Map<Integer, Integer> map ne…

SpringBoot系列——使用Spring Cache和Redis实现查询数据缓存

文章目录 1. 前言2. 缓存2.1 什么是缓存2.2 使用缓存的好处2.3 缓存的成本2.4 使用Spring Cache和Redis的优点 3. Spring Cache基础知识3.1 Spring Cache的核心概念3.2 Spring Cache的注解3.2.1 SpEL表达式3.2.2 Cacheable3.2.3 CachePut3.2.4 CacheEvict 4. 实现查询数据缓存4…

eclipse创建maven项目

第一步&#xff1a;打开eclipse 我们选择java项目即可 点击finish即可 它会自动下载插件 然后在控制台上输入Y即可

C语言 | Leetcode C语言题解之第150题逆波兰表达式求值

题目&#xff1a; 题解&#xff1a; int evalRPN(char** tokens, int tokensSize) {int n tokensSize;int stk[(n 1) / 2];memset(stk, 0, sizeof(stk));int index -1;for (int i 0; i < n; i) {char* token tokens[i];if (strlen(token) > 1 || isdigit(token[0])…

LeetCode | 28.找出字符串中第一个匹配项的下标 KMP

这是字符串匹配问题&#xff0c;朴素做法是两重遍历&#xff0c;依次从主串的i位置开始查看是否和模式串匹配&#xff0c;若不匹配就换下一个位置进行判断&#xff0c;直到找到或者遍历完&#xff0c;时间复杂度 O ( m n ) O(m \times n) O(mn) 还可以对主串进行处理&#xff…

Django 5 Web应用开发实战

文章目录 一、内容简介二、目录内容三、值得一读四、适读人群 一、内容简介 《Django 5 Web应用开发实战》集Django架站基础、项目实践、开发经验于一体&#xff0c;是一本从零基础到精通Django Web企业级开发技术的实战指南。《Django 5 Web应用开发实战》内容以Python 3.x和…

边坡监测规范:确保边坡工程安全稳定的专业准则

边坡工程是土木工程中不可或缺的一部分&#xff0c;其安全性直接关系到工程整体的质量与稳定性。因此&#xff0c;在边坡工程中实施有效的监测措施&#xff0c;遵循一系列专业的监测规范&#xff0c;对于预防边坡失稳、滑坡等灾害的发生&#xff0c;保障人民群众的生命财产安全…

Leetcode 力扣119. 杨辉三角 II (抖音号:708231408)

给定一个非负索引 rowIndex&#xff0c;返回「杨辉三角」的第 rowIndex 行。 在「杨辉三角」中&#xff0c;每个数是它左上方和右上方的数的和。 示例 1: 输入: rowIndex 3 输出: [1,3,3,1]示例 2: 输入: rowIndex 0 输出: [1]示例 3: 输入: rowIndex 1 输出: [1,1]提示…

Golang | Leetcode Golang题解之第150题逆波兰表达式求值

题目&#xff1a; 题解&#xff1a; func evalRPN(tokens []string) int {stack : make([]int, (len(tokens)1)/2)index : -1for _, token : range tokens {val, err : strconv.Atoi(token)if err nil {indexstack[index] val} else {index--switch token {case ""…

Java | Leetcode Java题解之第150题逆波兰表达式求值

题目&#xff1a; 题解&#xff1a; class Solution {public int evalRPN(String[] tokens) {int n tokens.length;int[] stack new int[(n 1) / 2];int index -1;for (int i 0; i < n; i) {String token tokens[i];switch (token) {case "":index--;stack…

【ElasticSearch】windows server 2019安装ES8.9.1 + kibana8.9.1 + IK分词器

目录 准备工作 ES Kibana IK 安装 es es访问测试 将es安装为系统服务 Kibana 配置es 运行kibana 访问测试 IK 补充 准备工作 ES8.9.1 kibana8.9.1 IK的版本最好要对应上&#xff01;&#xff01;&#xff01; ES es8.9.1&#xff1a; https://artifa…

[大模型]Phi-3-mini-4k-Instruct Lora 微调

本节我们简要介绍如何基于 transformers、peft 等框架&#xff0c;对 Phi-3-mini-4k-Instruct 模型进行 Lora 微调。Lora 是一种高效微调方法&#xff0c;深入了解其原理可参见博客&#xff1a;知乎|深入浅出 Lora。 这个教程会在同目录下给大家提供一个 nodebook 文件&#x…

简单了解RS485与RS232(UART)

简单了解RS485与RS232&#xff08;UART&#xff09; 一、UART和RS232、RS485的关系1、UART2、RS232/RS4853、RS232 与 RS485 的区别与联系 二、Modbus协议说明1、什么是协议2、Modbus协议说明3、Modebus通信过程4、Modbus存储区5、Modbus协议类型6、Modbus功能码 三、stm32HC-S…

【StableDiffusion】采样方法对比优缺点及评估,采样器 调度器(目前已有的 采样器介绍与评估)

采样器 Sampler 采样方法 决定了 如何从 噪声 生成 图像 的过程&#xff0c;也就是去噪过程如何进行 包含 DPM 的采样方法&#xff08;逆转扩散采样&#xff09; DPM → Diffusion Probabilistic Models&#xff08;扩散概率模型&#xff09; DPM、DPM2 包含 DPM 的采样方…