04-springIOC03-通过配置类实现IOC

news/2025/10/5 16:39:22/文章来源:https://www.cnblogs.com/benzhong/p/19126698
04-springIOC03-通过配置类实现IOC

Spring IOC基于Java配置类详解

一、IOC容器核心概念

1.1 什么是IOC(控制反转)

// 传统方式:手动创建对象,控制权在程序员手中
Student student = new Student();
student.setName("张三");// IOC方式:控制权交给Spring容器
ApplicationContext context = new AnnotationConfigApplicationContext(StuConfig.class);
Student student = context.getBean("stu");

核心思想:将对象的创建、依赖注入、生命周期管理交给容器处理,实现解耦。

1.2 DI(依赖注入)

public class Student {private Address address;  // 依赖关系// Spring容器负责注入Address对象public void setAddress(Address address) {this.address = address;}
}

二、实体类详解

2.1 Student类分析

public class Student {// 1. 属性定义private Address address;  // 对象类型属性private Integer id;       // 基本包装类型private String name;      // 字符串类型private Integer age;      // 数值类型// 2. 默认构造方法 - Spring创建对象时调用public Student() {System.out.println("Student无参构造器被调用");}// 3. Setter方法 - Spring通过setter注入依赖public void setAddress(Address address) {System.out.println("setAddress方法被调用");this.address = address;}// 4. Getter方法 - 获取属性值public Address getAddress() {return address;}// 5. toString方法 - 对象信息展示@Overridepublic String toString() {return "Student{" +"address=" + address +", id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}

2.2 Address类分析

public class Address {private String loc;  // 地址信息// 无参构造 - Spring默认使用public Address() {System.out.println("Address无参构造器被调用");}// 有参构造 - 可用于构造器注入public Address(String loc) {this.loc = loc;}// Setter/Getter方法public void setLoc(String loc) {this.loc = loc;}public String getLoc() {return loc;}
}

三、配置类深度解析

3.1 @Configuration注解

@Configuration  // 标识这是一个Spring配置类
public class StuConfig {// 配置类的作用:替代传统的applicationContext.xml文件// Spring容器会扫描这个类中的所有@Bean方法
}

@Configuration的作用

  • 告诉Spring这是一个配置类
  • 包含一个或多个@Bean方法
  • 替代XML配置文件

3.2 @Bean注解详解

@Bean("stu")  // 将方法返回值注册为Spring Bean
public Student student() {// 1. 创建依赖对象Address address = new Address();address.setLoc("毕节");// 2. 创建主对象Student student = new Student();// 3. 设置属性值 - 这就是依赖注入的过程student.setId(1001);        // 注入基本类型值student.setAge(18);         // 注入数值类型值  student.setName("刘备");     // 注入字符串值student.setAddress(address); // 注入对象依赖// 4. 返回完整对象return student;
}

@Bean注解的重要特性

  1. Bean命名

    @Bean              // 默认Bean名:student(方法名)
    @Bean("stu")       // 指定Bean名:stu
    @Bean(name = "studentBean") // 指定Bean名:studentBean
    
  2. 初始化过程

    创建Address对象 → 设置loc属性 → 创建Student对象 → 
    依次调用setter方法注入属性 → 返回完整Student对象
    
  3. 单例模式

    @Bean
    @Scope("singleton") // 默认单例,整个Spring容器中只有一个实例
    public Student student() {return new Student();
    }@Bean  
    @Scope("prototype") // 原型模式,每次获取都创建新实例
    public Student student() {return new Student();
    }
    

四、测试类执行流程分析

4.1 容器初始化过程

public static void main(String[] args) {// 1. 创建基于注解的Spring容器ApplicationContext applicationContext = new AnnotationConfigApplicationContext(StuConfig.class);// 执行流程:// Step1: 加载StuConfig配置类// Step2: 扫描@Configuration注解// Step3: 执行所有@Bean方法创建Bean实例// Step4: 将Bean存入Spring容器// 2. 从容器中获取BeanStudent student = (Student) applicationContext.getBean("stu");// 3. 使用BeanSystem.out.println(student);
}

4.2 详细执行时序

1. new AnnotationConfigApplicationContext(StuConfig.class)↓
2. Spring扫描StuConfig类,发现@Configuration注解↓  
3. Spring找到@Bean("stu")方法,执行student()方法↓
4. 执行new Address() → 调用Address无参构造器↓
5. 执行address.setLoc("毕节")↓
6. 执行new Student() → 调用Student无参构造器↓
7. 依次执行student对象的setter方法注入属性↓
8. 将完整的Student对象放入Spring容器,命名为"stu"↓
9. applicationContext.getBean("stu")从容器获取对象↓
10. 调用student.toString()方法输出结果

五、核心知识点总结

5.1 必须掌握的注解

注解 作用 使用场景
@Configuration 标记配置类 替代XML配置文件
@Bean 注册Bean到容器 在配置类中定义Bean

5.2 关键类说明

类名 作用 重要方法
ApplicationContext Spring容器接口 getBean()
AnnotationConfigApplicationContext 基于注解的容器 构造方法接收配置类

5.3 Bean创建流程

配置类 → @Bean方法 → 创建对象 → 属性注入 → 存入容器 → 获取使用

5.4 与传统XML配置对比

XML配置方式

<bean id="stu" class="com.zhongge.entity.Student"><property name="id" value="1001"/><property name="name" value="刘备"/><property name="age" value="18"/><property name="address" ref="address"/>
</bean><bean id="address" class="com.zhongge.entity.Address"><property name="loc" value="毕节"/>
</bean>

Java配置类优势

  • 类型安全:编译时检查
  • 功能强大:可在方法中使用Java逻辑
  • 易于重构:IDE支持良好
  • 简洁直观:代码即配置

六、扩展练习

6.1 尝试修改配置

@Bean("student2")
public Student createStudent() {Address address = new Address();address.setLoc("北京");Student student = new Student();student.setId(1002);student.setAge(20);student.setName("关羽");student.setAddress(address);return student;
}

6.2 测试多个Bean

public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(StuConfig.class);// 获取不同名称的BeanStudent stu1 = (Student) context.getBean("stu");Student stu2 = (Student) context.getBean("student2");System.out.println("stu1: " + stu1);System.out.println("stu2: " + stu2);
}

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

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

相关文章

网站建设公司厦门wordpress上长缺少临时文件夹

目录 3. 使用 Microsoft 证书颁发机构创建 VMCA 证书模板3.1 打开 Certificate Template Console3.2 复制模板修改 Compatibility 选项卡修改 General 选项卡修改 Extensions 选项卡确认新模板 4. 将新模板添加到证书模板4.1 打开 Certificate Console4.2 创建证书模板 关联博文…

完整教程:爬虫--以爬取小说为例

完整教程:爬虫--以爬取小说为例pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco&qu…

2025.10

不能再摆了吧Todolist:118e 的形式化理解方法,做一下 abc426,感觉有点难度,abc425f 的 poly 做法,149d 的 universal 做法,有交合并的复杂度证明,1554e 更快的做法。 [ARC121E] Directed Tree 考虑容斥转化为 \…

PCIe扫盲——物理层逻辑部分基础(一)

首先,回顾一下,之前看了很多遍的PCIe的Layer结构图:PCIe中的物理层主要完成编解码(8b/10b for Gen1&Gen2,128b/130b for Gen3 and later)、扰码与解扰码、串并转换、差分发送与接收、链路训练等功能。其中链…

旅游 便宜 网站建设做信息采集的网站

随着移动互联网的飞速发展&#xff0c;手机群控技术在市场推广、自动化测试、应用管理等领域的应用越来越广泛&#xff0c;手机群控软件作为一种能够同时控制多台手机设备的工具&#xff0c;其开发过程中&#xff0c;源代码的编写显得尤为重要。 1、设备连接与识别模块 设备连…

个人链接怎么制作湛江seo

网络通讯&#xff1a; 就是要把特定意义的数据通过物理介质传送给对方。把电信号变成有意义的数据&#xff1a; 以字节为单位分组&#xff0c;标识好每一组电信号的信息特征&#xff0c;按照分组的顺序来依次发送。 以太网规定&#xff1a;一组电信号为一个数据包&#xff0c…

做100个网站网站开发与硬件合同

在 Java中&#xff0c;有许多数字处理的类&#xff0c;比如Integer 类。但是Integer 类有一定的局限性&#xff0c;下面我们就来看看比 Integer 类更厉害的一个&#xff0c;BigInteger类。BigInteger类型的数字范围较 Integer 类型的数字范围要大得多。我们都知道 Integer 是 I…

网站建设方案 filetype doc百度快照推广有效果吗

目录 &#x1f345;点击这里查看所有博文 随着自己工作的进行&#xff0c;接触到的技术栈也越来越多。给我一个很直观的感受就是&#xff0c;某一项技术/经验在刚开始接触的时候都记得很清楚。往往过了几个月都会忘记的差不多了&#xff0c;只有经常会用到的东西才有可能真正记…

04-delphi10.3下PDFium5.8的PdfView1查找文本

04-delphi10.3下PDFium5.8的PdfView1查找文本https://www.cnblogs.com/txgh/p/15807085.html 在窗体上放置TPdfView组件PdfView1和TPdf组件Pdf1,并设置PdfView1的Pdf属性指向Pdf1 增加PdfView1的OnPaint事件PdfView1…

仅需3%训练数据的文本归一化技术

Proteno模型革新文本归一化技术,仅需传统方法3%的训练数据即可实现高性能,支持多语言处理,显著降低数据标注需求并减少不可接受错误,适用于语音合成系统的快速部署。仅需3%训练数据的文本归一化技术 在语音合成系统…

价值原语博弈协议:价值原语共识锚定原则

价值原语博弈协议:价值原语共识锚定原则目的 为价值原语博弈确立明确的操作边界,防止无限递归解构,确保系统在价值冲突场景中能快速转向解决方案构建。原则定义 当解构复杂价值主张至某一颗粒度时,若冲突各方均承认…

实用指南:工作流引擎-16-开源审批流项目之 整合Flowable官方的Rest包

实用指南:工作流引擎-16-开源审批流项目之 整合Flowable官方的Rest包pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: &q…

高密哪里做网站好许昌建设网站哪家好

使用python爬虫实现百度翻译功能 python爬虫实现百度翻译&#xff1a; python解释器【模拟浏览器】&#xff0c;发送【post请求】&#xff0c;传入待【翻译的内容】作为参数&#xff0c;获取【百度翻译的结果】 通过开发者工具&#xff0c;获取发送请求的地址 提示&#xff1a;…

网站推广论坛网络营销策划

自定义取出第几个分割字符前的字符串&#xff0c;默认位置&#xff08;0&#xff09;格式&#xff1a;dbo.split(字段名,分隔字符,取出的第几个字符串)如果没有分隔的字符&#xff0c;则返回整个字符串。如果取出的位置字符串的位置超出Index则返回空。CREATE FUNCTION [dbo].[…

开网站要多少钱中国铁道建设协会网站

图像的灰度处理的三种方法&#xff1a; 1.imread的方法将像素值修改为0 2.调用一个RGB转灰度的方法实现灰度转化&#xff08;cv2.COLOR_BGR2GRAY&#xff09; 3.R G B 的均值取灰度值来灰度转化&#xff08;原理&#xff09; 处理结果 如下: 转载于:https://www.cnblogs.com/Ja…

个人建网站步骤wordpress+订单号位数

目录 单词搜索&#xff08;搜索&#xff09; 题目解析 讲解算法原理 编写代码 杨辉三⻆&#xff08;动态规划&#xff09; 题目解析 讲解算法原理 编写代码 单词搜索&#xff08;搜索&#xff09; 题目解析 1.题目链接&#xff1a;单词搜索_牛客题霸_牛客网 2.题目描…

25fall做题记录-October - Amy

2025.10.5 Sale n,m=map(int,input().split()) a=list(map(int,input().split())) a.sort() s=0 for i in range(len(a)):if(a[i]<0 and i+1<=m):s-=a[i]if(a[i]>=0):break print(s)Maya Calendar 这题很难评…

嗯嗯

https://www.luogu.com.cn/problem/CF1874F 考虑容斥。发现当 \([l_1,r_1]\) 和 \([l_2,r_2]\) 有交且不包含,且均为坏区间时,\([l_1,l_2-1]\) 也是坏区间。所以在容斥时,只要钦定了 \([l_1,r_1]\) 和 \([l_2,r_2]\…

什么网站可以接单做设计方案外贸公司怎么做网站

本节书摘来华章计算机《深入理解Elasticsearch&#xff08;原书第2版&#xff09;》一书中的第2章 &#xff0c;第2.3.3节&#xff0c;[美]拉斐尔酷奇&#xff08;Rafal Ku&#xff09; 马雷克罗戈任斯基&#xff08;Marek Rogoziski&#xff09;著 张世武 余洪淼 商旦 译 …

完整教程:HTTPS

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …