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.mzph.cn/bicheng/26976.shtml

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

相关文章

通用与垂直大模型:应用、挑战与未来发展

本文全面探讨了通用大模型和垂直大模型在人工智能、互联网行业以及教育领域的应用、优势、挑战和未来发展趋势。大模型的发展正经历分化&#xff0c;通用大模型和垂直大模型各有侧重&#xff0c;共同推动AI技术进步和商业智能变革。 文章目录 1.1 通用大模型的定义与特点1.2 垂…

力扣1482.制作m束花所需的最少时间

力扣1482.制作m束花所需的最少时间 二分答案 check的时候 用一个bool数组判断是否开花找连续的k朵花 const int N 1e510;int st[N];class Solution {public:int minDays(vector<int>& bloomDay, int m, int k) {int n bloomDay.size();if(n < (long long)m*…

DDPM公式推导(一)

去噪扩散概率模型 Title:Denoising Diffusion Probabilistic Models paper是UC Berkeley发表在NIPS 2020的工作 paper地址 Abstract 我们使用扩散概率模型&#xff08;一类受非平衡热力学启发的潜在变量模型&#xff09;展示了高质量的图像合成结果。根据扩散概率模型与采用La…

(一)PHP 变量

1.声明变量 要点&#xff1a;PHP声明变量用一个“$”符号&#xff1b;PHP变量名是区分大小写的&#xff1b;变量名可以用下划线开头&#xff0c;不能用数字开头&#xff0c;和语言类似&#xff1b; 2.变量的赋值 2.1直接赋值 和C语言一样&#xff0c;不多说。eg. $a"dd…

开源可二次开发的商城小程序源码系统源码 前后端分离 附带完整的安装包以及搭建部署教程

系统概述 本开源商城小程序源码系统是基于现代Web开发技术栈打造的一套高性能、易扩展的电商解决方案。它采用了前后端分离的设计模式&#xff0c;前端使用Vue.js或React等主流框架构建用户界面&#xff0c;后端则采用Node.js/Express、Spring Boot等技术栈处理业务逻辑与数据…

【npm】console工具(含胶囊,表格,gif图片)

这是一款控制台花样输出工具 相对丰富的输出方式 文本输出属性值输出胶囊样式输出表格输出图片输出&#xff08;含动图&#xff09; 安装 npm install v_aot引用 import v_aot from "v_aot";字段说明 字段类型属性字符串值字符串类型default 、 primary 、 suc…

可再生能源的未来——Kompas.ai如何助力绿色发展

引言 在全球气候变化和能源危机的背景下&#xff0c;可再生能源逐渐成为能源发展的重要方向。本文将探讨可再生能源的发展趋势&#xff0c;并介绍Kompas.ai如何通过AI技术助力绿色发展的实现。 可再生能源的发展及其重要性 可再生能源是指通过自然资源产生的能源&#xff0c;…

【投稿优惠|权威主办】2024年能源、智能制造与材料科学国际学术会议(ICEIMMS 2024)

【投稿优惠|权威主办】2024年能源、智能制造与材料科学国际学术会议&#xff08;ICEIMMS 2024&#xff09; 2024 International Academic Conference on Energy, Intelligent Manufacturing, and Materials Science&#xff08;ICEIMMS 2024&#xff09; ▶会议简介 2024年能源…

大语言模型 (LLM) 红队测试:提前解决模型漏洞

大型语言模型 (LLM) 的兴起具有变革性&#xff0c;以其在自然语言处理和生成方面具有与人类相似的卓越能力&#xff0c;展现出巨大的潜力。然而&#xff0c;LLM 也被发现存在偏见、提供错误信息或幻觉、生成有害内容&#xff0c;甚至进行欺骗行为的情况。一些备受关注的事件包括…

《分析模式》第2章中文UML图(已修正原书错误)(2.1-2.6)

DDD领域驱动设计批评文集 做强化自测题获得“软件方法建模师”称号 《软件方法》各章合集 &#xff08;1&#xff09;已用UML、OCL表示&#xff0c;并翻译为中文。 &#xff08;2&#xff09;已修正原书图存在的错误&#xff08;多重性、角色&#xff09;&#xff0c;之前的…

企业服务器上云还是下云哪种比较好?-尚云Sunclouds

如今很多中小企业都面临一个艰难的选择&#xff0c;是要选择将服务器迁移至数据中心托管&#xff08;下云&#xff09;或者直接迁移到云端&#xff08;上云&#xff09;。中小企业是社会发展的中坚力量&#xff0c;他们的特点少而明显&#xff1a;资金少&#xff0c;增长快&…

tkinter文件选择对话框

tkinter文件选择对话框 Tkinter 文件选择对话框效果代码 Tkinter 文件选择对话框 Tkinter 提供以下文件选择对话框&#xff1a; tkinter.filedialog.askopenfilename()&#xff1a;打开文件对话框&#xff0c;选择单个文件。tkinter.filedialog.askopenfilenames()&#xff1…

2024最值得入手的骨传导耳机有几款?年度精选五款骨传导耳机分享

作为一个爱好运动的人来说&#xff0c;现在天气越来越暖和了&#xff0c;很多人选择外出徒步、越野或者骑行。在运动过程中都会佩戴一些入耳式耳机&#xff0c;但是运动一段时间发现入耳式耳机带久了耳朵会很不舒服&#xff0c;而且出汗了的话对于一些不防水的入耳式耳机的话&a…

每天一个数据分析题(三百六十七)- 头脑风暴因果图

头脑风暴因果图&#xff08;鱼骨图&#xff09;绘制过程中填上问题或现状的是在‘鱼’的哪个部位&#xff1f; A. 鱼尾 B. 鱼头 C. 脊椎 D. 鱼刺 数据分析认证考试介绍&#xff1a;点击进入 题目来源于CDA模拟题库 点击此处获取答案

SpringBoot 大文件基于md5实现分片上传、断点续传、秒传

SpringBoot 大文件基于md5实现分片上传、断点续传、秒传 SpringBoot 大文件基于md5实现分片上传、断点续传、秒传前言1. 基本概念1.1 分片上传1.2 断点续传1.3 秒传1.4 分片上传的实现 2. 分片上传前端实现2.1 什么是WebUploader&#xff1f;功能特点接口说明事件APIHook 机制 …

MySQL查询数据库中所有表名表结构及注释以及生成数据库文档

MySQL查询数据库中所有表名表结构及注释 生成数据库文档在后面&#xff01;&#xff01;&#xff01; select t.TABLE_COMMENT -- 数据表注释 , c.TABLE_NAME -- 表名称 , c.COLUMN_COMMENT -- 数据项 , c.COLUMN_NAME -- 英文名称 , -- 字段描述 , upper(c.DATA_TYPE) as …

开源大模型的新星:Gitcode上的热门项目推荐

在开源程序的世界里&#xff0c;每一个新的项目都像是夜空中的一颗新星&#xff0c;它们闪耀着独特的光芒&#xff0c;吸引着无数程序员的目光。今天&#xff0c;我将为大家推荐一个位于Gitcode平台的热门开源项目——"StarryAI"&#xff0c;这是一个旨在推动人工智能…

视频字幕提取工具怎么使用?不妨看看这些教程

在探索学习设备使用的过程中&#xff0c;视频教程扮演着极其重要的角色。 但是&#xff0c;我们可能会遇到一些挑战&#xff0c;比如长视频教程的观看效率不高&#xff0c;信息量大难以快速定位到关键点&#xff0c;或者有些人更喜欢阅读文字而非观看视频来学习。 为解决这一…

python-元组加法

在Python中&#xff0c;元组&#xff08;tuple&#xff09;是一种不可变的序列类型&#xff0c;你不能直接对元组进行加法操作。但是&#xff0c;你可以通过一些其他方式来处理元组的“加法”。 如果你想要“合并”两个元组&#xff0c;你可以使用加号&#xff08;&#xff09…

SQLite JDBC驱动程序

SQLite JDBC驱动程序下载地址&#xff1a; 下载地址