Spring中的IOC

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.mfbz.cn/a/716792.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

el-date-picker 有效时间精确到时分秒 且给有效时间添加标记

el-date-picker实现有效日期做标记且时分秒限制选择范围 代码如下&#xff1a; // html部分 <el-date-pickerv-model"dateTime"type"datetime":picker-options"pickerOptions" > </el-date-picker>// js部分 /*** 回放有效日期开始时…

WPF/C#:如何将数据分组显示

WPF Samples中的示例 在WPF Samples中有一个关于Grouping的Demo。 该Demo结构如下&#xff1a; MainWindow.xaml如下&#xff1a; <Window x:Class"Grouping.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x&q…

文心一言 VS 讯飞星火 VS chatgpt (283)-- 算法导论21.2 1题

一、使用链表表示和加权合并启发式策略&#xff0c;写出 MAKE-SET、FIND-SET 和 UNION 操作的伪代码。并指定你在集合对象和表对象中所使用的属性。如果要写代码&#xff0c;请用go语言。 文心一言&#xff1a; 在并查集&#xff08;Disjoint Sets&#xff09;或集合合并&…

6.7.29 基于卷积神经网络的乳腺良恶性图像分类

计算机化乳腺癌诊断系统在早期癌症诊断中发挥着重要作用。为此&#xff0c;应用深度学习&#xff0c;利用卷积神经网络 (CNN) 对基于小型乳房 X 线图像分析协会 (mini-MIAS) 数据库的乳房 X 线图像中的异常&#xff08;良性或恶性&#xff09;进行分类。观察准确度、灵敏度和特…

天锐绿盾数据防泄密软件有哪些功能

天锐绿盾数据防泄密软件的功能丰富而全面&#xff0c;旨在从源头上保障企业数据的安全。以下是对其主要功能的归纳和介绍&#xff1a; www.drhchina.com 一、文件加密模块 透明加密&#xff1a;在不影响用户工作流程的前提下&#xff0c;对需要保护的文件进行自动加密处理。文…

unity 打包PC安装包中常见文件的功能

目录 前言 一、打包好的文件 二、常用文件 1.文件夹XXX_Data 2.文件夹MonoBleedingEdge 3.文件夹XXX_Data内部 三、文件的应用 1.如果你替换了一个图片 2.如果你新增了或减少了图片和资源 3.场景中有变动 4.resources代码加载的资源改了 5.如果你代码替换了 四、作…

大模型时代:消失的飞轮

在移动互联网时代&#xff0c;“数据飞轮”效应深入人心&#xff1a;场景催生应用&#xff0c;应用生成数据&#xff0c;继而这些数据反馈优化算法&#xff0c;再反哺应用本身&#xff0c;进入迭代优化的良性循环。 随着生成式人工智能的兴起&#xff0c;许多人认为这一飞轮效…

springboot原理篇-bean管理

springboot原理篇-bean管理&#xff08;二&#xff09; 我们今天主要学习IOC容器中Bean的其他使用细节&#xff0c;主要学习以下三方面&#xff1a; 如何从IOC容器中手动的获取到bean对象bean的作用域配置管理第三方的bean对象 一、获取Bean 了解即可&#xff0c;默认情况下…

基于Python的花卉识别分类系统【W9】

简介&#xff1a; 基于Python的花卉识别分类系统利用深度学习和计算机视觉技术&#xff0c;能够准确识别和分类各种花卉&#xff0c;如玫瑰、郁金香和向日葵等。这种系统不仅有助于植物学研究和园艺管理&#xff0c;还在生态保护、智能农业和市场销售等领域展现广泛应用前景。随…

可视化大屏搞这样,是对前端开发尊严的巨大挑战。

现在可视化大屏不搞点炫酷的效果和3D交互&#xff0c;出门都不好意思给别人打招呼&#xff0c;作为前端领域的老司机&#xff0c;我感觉尊严受到了巨大挑战&#xff0c;必须迎难而上&#xff0c;hold住他们&#xff0c;老铁们你们觉得呢&#xff1f;

构建高效API接口:五个关键技术要点解析

构建高效API接口是现代软件开发中至关重要的一环。以下是五个关键技术要点&#xff0c;它们可以帮助开发者设计、实现、和维护高性能的API接口&#xff1a; 1. RESTful设计原则和HTTP协议最佳实践 资源定位与可寻址性&#xff1a;为每个资源定义清晰的URL&#xff0c;使用HTT…

买灯必看!护眼台灯是智商税吗?护眼台灯真的有用吗?

随着人们健康意识的日益增强、儿童近视率的大幅度增加&#xff0c;眼睛健康逐渐成为人们关注的焦点。为了减轻长时间用眼带来的疲劳&#xff0c;许多人开始寻求高品质的照明设备来呵护双眼。照明技术的飞速发展&#xff0c;使得现代照明产品能够精准地调整光线亮度、色温和闪烁…

RTSP/Onvif安防监控平台EasyNVR抓包命令tcpdump使用不了,该如何解决?

安防视频监控汇聚EasyNVR智能安防视频监控平台&#xff0c;是基于RTSP/Onvif协议的安防视频平台&#xff0c;可支持将接入的视频流进行全平台、全终端分发&#xff0c;分发的视频流包括RTSP、RTMP、HTTP-FLV、WS-FLV、HLS、WebRTC等格式。平台可提供的视频能力包括&#xff1a;…

区间DP——AcWing 282. 石子合并

区间DP 定义 区间 DP 是动态规划的一种特殊形式&#xff0c;主要是在一段区间上进行动态规划计算。 运用情况 通常用于解决涉及在一段区间内进行操作、计算最优值等问题。比如计算一个区间内的最大子段和、最小分割代价等。一些常见的场景包括合并操作、划分操作等在区间上…

华火新能源集成灶评测:创新与品质的融合

在厨房电器的不断推陈出新中&#xff0c;华火新能源集成灶以其独特的魅力进入了人们的视野。今天&#xff0c;我们就来深入评测这款备受关注的产品——华火新能源集成灶 一、华火新能源集成灶的创新与环保 首先&#xff0c;我们先来探讨新能源集成灶的整体表现。华火新能源集成…

如何将扫描的 PDF 转换为 Word

您是否正在寻找一种可靠且轻松的方式将扫描的 PDF 文档转换为可编辑的 Word 文件&#xff1f;要将 PDF 转换为可编辑的 Word 文档&#xff0c;神奇之处在于光学字符识别(OCR)。 使用 PDFgear&#xff0c;您可以无缝地将扫描的 PDF 转换为 Word&#xff0c;无论是在线还是离线。…

【电子实验4】TDA2030功率放大电路

&#x1f6a9; WRITE IN FRONT &#x1f6a9; &#x1f50e; 介绍&#xff1a;"謓泽"正在路上朝着"攻城狮"方向"前进四" &#x1f50e;&#x1f3c5; 荣誉&#xff1a;2021|2022年度博客之星物联网与嵌入式开发TOP5|TOP4、2021|2222年获评…

【vue3|第8期】深入理解Vue 3 computed计算属性

日期&#xff1a;2024年6月10日 作者&#xff1a;Commas 签名&#xff1a;(ง •_•)ง 积跬步以致千里,积小流以成江海…… 注释&#xff1a;如果您觉得有所帮助&#xff0c;帮忙点个赞&#xff0c;也可以关注我&#xff0c;我们一起成长&#xff1b;如果有不对的地方&#xf…

Aptos Builder Jam 亚洲首站|议程公布,无限畅想 Aptos 生态未来

作为一个新兴的 Layer1 公链&#xff0c;Aptos 自诞生之日起的理想便是 “A Layer 1 for everyone” 当 Web3 深陷熊市阴影之时&#xff0c;Aptos 奋力为开发者找到了全新的技术路径&#xff0c;正有 200 项目正在开发&#xff0c;并且已有大量 DeFi 项目落实部署工作&#xff…

【Kubernetes】k8s 自动伸缩机制—— HPA 部署

一、在K8s中扩缩容分为两种&#xff1a; ●Node层面&#xff1a;对K8s物理节点扩容和缩容&#xff0c;根据业务规模实现物理节点自动扩缩容 ●Pod层面&#xff1a;我们一般会使用Deployment中的Replicas参数&#xff0c;设置多个副本集来保证服务的高可用&#xff0c;但是这是…