Spring对bean的管理
一.bean的实例化
1.spring通过反射调用类的无参构造方法
在pom.xml文件中导入坐标:
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.29</version></dependency></dependencies>
创建Student类:
public class Student {public Student(){System.out.println("执行student类的无参构造方法");}
}
在Application.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--====================bean的创建方式1(无参)===========================--><bean id="student" class="com.apesource.bean.Student"></bean></beans>
2.通过指定工厂创建bean
创建Student类:
public class Student {public Student(){}
}
在Application.xml文件中创建bean(工厂):
public class StudentFactory {public Student creatBean(){System.out.println("执行普通工厂");return new Student();}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--====================bean的创建方式2(工厂)===========================--><bean id="student" class="com.apesource.bean.Student"></bean><bean id="factory" class="com.apesource.factory.StudentFactory"></bean></beans>
3.通过指定静态工厂创建bean
创建Student类:
public class Student {public Student(){}
}
在Application.xml文件中创建bean(静态工厂):
public class StudentStaticFactory {public static Student creartBean(){System.out.println("执行静态工厂");return new Student();}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--====================bean的创建方式3(静态工厂)===========================--><bean id="student" class="com.apesource.factory.StudentStaticFactory" factory-method="creartBean"></bean>
</beans>
测试Test:
public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student = (Student) applicationContext.getBean("student");System.out.println(student);}
测试结果如下:



二.bean的作用域
语法:<bean scope="属性值"></bean>
属性:
singleton单例:spring只会为该bean对象只会创建唯一实例(默认)
<!--====================bean的作用域===========================--><bean id="student" class="com.apesource.bean.Student" scope="singleton"></bean>
运行结果:True,只创建一次,所以内存地址相同
public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student1 = (Student) applicationContext.getBean("student");Student student2 = (Student) applicationContext.getBean("student");System.out.println(student1==student2);}
}
prototype多例:每次获取bean,Spring会创建一个新的bean实例
<!--====================bean的作用域===========================--><bean id="student" class="com.apesource.bean.Student" scope="prototype"></bean>
运行结果:false 创建两次,所以内存地址不同
public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student1 = (Student) applicationContext.getBean("student");Student student2 = (Student) applicationContext.getBean("student");System.out.println(student1==student2);}
}
request:每一次HTTP请求,Spring会创建一个新的bean实例
session:不同的HTTP会话,Spring会创建不同的bean实例
三.bean的生命周期
实例化:springIOC创建对象,根据配置文件中Bean的定义,利用Java Reflection反射技术创建Bean的实例
属性赋值:springDI
初始化:
1.接口实现(执行InitializingBean初始化方法)
2.属性实现(执行init-method 自定义初始化方法)
操作使用
销毁:
1.接口实现(执行DisposableBean初始化方法)
2.属性实现(执行destroy-method自定义初始化方法)
public class Teacher implements InitializingBean, DisposableBean {public void doinit(){System.out.println("初始化(属性)");}public void dodestory(){System.out.println("销毁了(属性)");}public String tname;@Overridepublic void destroy() throws Exception {System.out.println("销毁了(接口)");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("初始化(接口)");}@Overridepublic String toString() {return "Teacher{" +"tname='" + tname + '\'' +'}';}public void setTname(String tname) {System.out.println("属性赋值");this.tname = tname;}public Teacher() {System.out.println("实例化");}
}
Application.xml文件配置:
<bean id="teacher" class="com.apesource.bean.Teacher" init-method="doinit" destroy-method="dodestory"><property name="tname" value="老师"></property></bean>
测试代码:
public class Test01 {public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Teacher teacher = (Teacher) applicationContext.getBean("teacher");System.out.println(teacher);applicationContext.close(); //关闭spring容器}
}
运行结果:

四.bean的自动装配
spring的配置
1.spring2.5前==xml
2.spring2.5后==xml+annotation
3.spring3.0后==annotation+JavaConfig配置类
spring2.5后=xml+annotation
目的优化一下代码:
<bean id="" class="" init-method="" destroy-method="" scope=""><property></property><constructor-arg></constructor-arg></bean>
注解:
1.注入类
替换:
<bean id="" class=""></bean>
位置:类
语法:
@Component
eg:Class User{}
<bean id="user" class="com.apesource.包.User"></bean>
||等价于||
@Component
Class User{}
语法:@Component(value="注入容器中的id,如果省略id为类名且首字母小写,value属性名称可以省略")
<context:component-scan base-package=""></context:component-scan>
含义:扫描所有被@Component注解所修饰的类,注入容器
@Repository=====>注入数据访问层
@Service========>注入业务层
@Controller=====>注入控制层
以上三个注解与@Component功能语法一致
2.注入基本数据
@Value
含义:注入基本数据
替换:<property></property>
修饰:成员变量或对应的set方法
语法:@Value("数据内容")
@Value("${动态获取}")
注意:不能单独用必须配合
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
@Autowired
语法:@Autowired(required = "true-默认、false、是否必须进行装配")
修饰:成员变量或对应的set方法
含义:按照通过set方法进行“类型装配”,set方法可以省略
注意:
1.默认是按照类型装配且同set方法
2.若容器中有一个类型可以与之匹配则装配成功,若没有一个类型可以匹配则报错NoSuchBeanDefinitionException

3.若容器中有多个类型可以与之匹配,则自动切换为按照名称装配,若名称没有对应,则报错NoUniqueBeanDefinitionException

3.其他注解
@Primary
@Component
@Primary//首选
public class AccountDaoImp2 implements IAccountDao{@Overridepublic void save() {System.out.println("dao2的新增");}
}
含义:首选项,当类型冲突的情况下,此注解修饰的类被列为首选(备胎扶正)
修饰:类
注意:不能单独使用,必须与@Component....联合使用
@Qualifier(value="名称")
@Component("service")
public class AccountServiceImp implements IAccountService {@Autowired@Qualifier(value = "accountDaoImp1")private IAccountDao dao;@Overridepublic void save() {System.out.println("service的新增");dao.save();}
}
含义:按照名称装配
修饰:成员变量
注意:不能单独使用,必须与@Autowired联合使用
@Resource(name="名称")
@Component("service")
public class AccountServiceImp implements IAccountService {@Resource(name="accountDaoImp2")private IAccountDao dao;@Overridepublic void save() {System.out.println("service的新增");dao.save();}
}
含义:按照名称装配
修饰:成员变量
注意:单独使用
@Scope
@Component
@Scope("prototype")
@Scope("singleton")
public class AccountDaoImp2 implements IAccountDao{@Overridepublic void save() {System.out.println("dao2的新增");}
}
替换:<bean scope="替换"></bean>
含义:配置类的作用域
修饰:类
注意:不能单独使用,必须与@Component....联合使用
@Scope("prototype") 单例
@Scope("singleton") 多例
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@PostConstruct:初始化,修饰方法
替换:<bean init-method=""></bean>
@PreDestroy:销毁,修饰方法
替换:<bean destory-method=""></bean>
@PostConstruct
public void doinit(){System.out.println("初始化");
}@PreDestroy
public void dodestory(){System.out.println("销毁了");
}
Spring3.0=====JavaConfig+annonation
此类充当配置类,替代applicationContext.xml文件
spring中的新注解
@Configuration
@Configuration
作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
@ComponentScan
@ComponentScan(basePackages = {"com.apesource"})
作用:用于通过注解指定spring在创建容器时要扫描的包
属性:
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
我们使用此注解就等同于在xml中配置了:
<context:component-scan base-package="com.apesource"></context:component-scan>
@Bean
//注入id为方法名teacher类型为Teacher的JavaBean
@Bean
public Teacher teacher(){return new Teacher();
}//注入id为方法名abc类型为Teacher的JavaBean
@Bean(name = "abc")
public Teacher teachers(){return new Teacher();
}//注入id为方法名dao类型为AccountDao的JavaBean
@Bean
public IAccountDao dao(){return new AccountDaoImp1();
}//注入id为方法名time类型为Date的JavaBean
@Bean
public Date time(){return new Date();
}
作用:用于把当前方法的返回值作为bean对象存入spring的容器中
属性:
name:用于指定bean的id。当不写时,默认值是当前方法的名称
@Import
@Import(DataSourceConfig.class)
作用:用于导入其他的配置类
属性:
value:用于指定其他配置类的字节码。
例子:@Import(SystemSpringConfig.class)
@PropertySource
@PropertySource(value = "classpath:msg.properties")
作用:用于指定properties文件的位置
属性:
value:指定文件的名称和路径。
关键字:classpath,表示类路径下
配合@Value使用
例子:@PropertySource("classpath:SystemSpringConfig.properties")
相关文章:
Spring对bean的管理
一.bean的实例化 1.spring通过反射调用类的无参构造方法 在pom.xml文件中导入坐标: <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.29<…...
Character Controller Smooth
流畅的角色控制器 Unity的FPS解决方案! 它是一种具有非常平滑运动和多种设置的解决方案: - 移动和跳跃 - 坐的能力 - 侧翻角度 - 不平整表面的处理 - 惯性守恒 - 重力 - 与物理物体的碰撞。 - 支持没有家长控制的平台 此解决方案适用于那些需要角色控制器…...
企业内训系统源码开发实战:搭建实践与经验分享
本篇文章中,小编将带领读者深入探讨企业内训系统的源码开发实战,分享在搭建过程中遇到的挑战与解决方案。 一、项目规划与需求分析 通过对企业内训需求的深入了解,我们可以更好地定义系统架构和数据库设计。 二、技术栈选择 在内训系统开发…...
15.三数之和(双指针,C解答附详细分析)
题目描述: 给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! j、i ! k 且 j ! k ,同时还满足 nums[i] nums[j] nums[k] 0 。请 你返回所有和为 0 且不重复的三元组。 注意:答案中不可以包含…...
SpringCloud微服务 【实用篇】| Dockerfile自定义镜像、DockerCompose
目录 一:Dockerfile自定义镜像 1. 镜像结构 2. Dockerfile语法 3. 构建Java项目 二: Docker-Compose 1. 初识DockerCompose 2. 部署微服务集群 前些天突然发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,…...
Vue3+TS+ElementPlus的安装和使用教程【详细讲解】
前言 本文简单的介绍一下vue3框架的搭建和有关vue3技术栈的使用。通过本文学习我们可以自己独立搭建一个简单项目和vue3的实战。 随着前端的日月更新,技术的不断迭代提高,如今新vue项目首选用vue3 typescript vite pinia……模式。以前我们通常使用…...
浅析锂电池保护板(BMS)系统设计思路(四)SOC算法-扩展Kalman滤波算法
BMS开发板 1 SOC估算方法介绍 电池SOC的估算是电池管理系统的核心,自从动力电池出现以来,各种各样的电池SOC估算方法不断出现。随着电池管理系统的逐渐升级,电池SOC估算方法的效率与精度不断提高,下面将介绍常用几种电池SOC估算方…...
构建异步高并发服务器:Netty与Spring Boot的完美结合
前言 「作者主页」:雪碧有白泡泡 「个人网站」:雪碧的个人网站 ChatGPT体验地址 文章目录 前言IONetty1. 引入依赖2. 服务端4. 客户端结果 总结引导类-Bootstarp和ServerBootstrap连接-NioSocketChannel事件组-EventLoopGroup和NioEventLoopGroup 送书…...
uniapp实现文字超出宽度自动滚动(在宽度范围之内不滚动、是否自动滚动、点击滚动暂停)
效果如下: 文字滚动 组件代码: <template><view class="tip" id="tip" @tap.stop="clickMove"><view class=...
win11 电脑睡眠功能失效了如何修复 win11 禁止鼠标唤醒
1、win11睡眠不管用怎么办,win11电脑睡眠功能失效了如何修复 在win11系统中拥有许多令人激动的新功能和改进,有些用户在使用win11电脑时可能会遇到一个问题:睡眠模式不起作用。当他们尝试将计算机置于睡眠状态时,却发现系统无法进…...
内坐标转换计算
前言 化学这边的库太多了。 cs这边的库太少了。 去看化学的库太累了。 写一个简单的实现思路,让cs的人能看懂。 向量夹角的范围 [0, pi) 这是合理的。 因为两个向量只能构成一个平面系统,平面系统内的夹角不能超过pi。 二面角的范围 涉及二面角&…...
vue中 components自动注册,不需要一个个引入注册方法
1.在compontents文件夹新建js文件 componentRegister 不能引用文件夹里的组件** import Vue from "vue"; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() string.slice(1); } const requireComponent require.context( ".…...
web自动化测试从入门到持续集成
在很多刚学习自动化的可能会认为我只需要会运用selenium,我只需要在一个编辑器中实用selenium java编写了一些脚本那么就会自动化了,是真的吗?答案肯定是假的。自动化肯定是需要做到真的完全自动化,那如何实现呢?接着往…...
python小工具之弱密码检测工具
一、引用的python模块 Crypto: Python中一个强大的加密模块,提供了许多常见的加密算法和工具。它建立在pyc.ypodome或pyc.ypto等底层加密库之上,为Python程序员提供了简单易用的API,使其可以轻松地实现各种加密功能。 commands…...
链接器--动态链接器--延迟绑定与动态链接器是什么?学习笔记二
内容在下面链接(通过新建标签页打开): 链接器--动态链接器--延迟绑定与动态链接器是什么?学习笔记二一个例子来看延迟加载https://mp.weixin.qq.com/s?__bizMzkyNzYzMjMzNA&mid2247483713&idx1&snee90a5a7d59872287…...
JMeter CSV 参数文件的使用方法
.在 JMeter 测试中,参数化是非常重要的,参数化允许我们模拟真实世界中的各种情况。本文我们将探讨如何在 JMeter 中使用 CSV 参数文件。 创建 CSV 文件 首先,我们需要创建一个逗号分隔的值(CSV)文件,其中…...
how2heap-2.23-06-unsorted_bin_into_stack
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h>// 从 unsorted bin 的 bk 去找合适的 void jackpot(){ fprintf(stderr, "Nice jump d00d\n"); exit(0); }int main() {intptr_t stack_buffer[4] {0};fpr…...
(学习打卡2)重学Java设计模式之六大设计原则
前言:听说有本很牛的关于Java设计模式的书——重学Java设计模式,然后买了(*^▽^*) 开始跟着小傅哥学Java设计模式吧,本文主要记录笔者的学习笔记和心得。 打卡!打卡! 六大设计原则 (引读:这里…...
数据结构:第7章:查找(复习)
目录 顺序查找: 折半查找: 二叉排序树: 4. (程序题) 平衡二叉树: 顺序查找: ASL 折半查找: 这里 j 表示 二叉查找树的第 j 层 二叉排序树: 二叉排序树(Binary Search Tree&…...
编程语言的未来?
编程语言的未来? 随着科技的飞速发展,编程语言在计算机领域中扮演着至关重要的角色。它们是软件开发的核心,为程序员提供了与机器沟通的桥梁。那么,在技术不断进步的未来,编程语言的走向又将如何呢? 在技…...
TDengine 快速体验(Docker 镜像方式)
简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能,本节首先介绍如何通过 Docker 快速体验 TDengine,然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker,请使用 安装包的方式快…...
【力扣数据库知识手册笔记】索引
索引 索引的优缺点 优点1. 通过创建唯一性索引,可以保证数据库表中每一行数据的唯一性。2. 可以加快数据的检索速度(创建索引的主要原因)。3. 可以加速表和表之间的连接,实现数据的参考完整性。4. 可以在查询过程中,…...
CentOS下的分布式内存计算Spark环境部署
一、Spark 核心架构与应用场景 1.1 分布式计算引擎的核心优势 Spark 是基于内存的分布式计算框架,相比 MapReduce 具有以下核心优势: 内存计算:数据可常驻内存,迭代计算性能提升 10-100 倍(文档段落:3-79…...
渲染学进阶内容——模型
最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...
什么是EULA和DPA
文章目录 EULA(End User License Agreement)DPA(Data Protection Agreement)一、定义与背景二、核心内容三、法律效力与责任四、实际应用与意义 EULA(End User License Agreement) 定义: EULA即…...
汇编常见指令
汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX(不访问内存)XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...
网站指纹识别
网站指纹识别 网站的最基本组成:服务器(操作系统)、中间件(web容器)、脚本语言、数据厍 为什么要了解这些?举个例子:发现了一个文件读取漏洞,我们需要读/etc/passwd,如…...
Kubernetes 网络模型深度解析:Pod IP 与 Service 的负载均衡机制,Service到底是什么?
Pod IP 的本质与特性 Pod IP 的定位 纯端点地址:Pod IP 是分配给 Pod 网络命名空间的真实 IP 地址(如 10.244.1.2)无特殊名称:在 Kubernetes 中,它通常被称为 “Pod IP” 或 “容器 IP”生命周期:与 Pod …...
系统掌握PyTorch:图解张量、Autograd、DataLoader、nn.Module与实战模型
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在聚客AI学院。 本文通过代码驱动的方式,系统讲解PyTorch核心概念和实战技巧,涵盖张量操作、自动微分、数据加载、模型构建和训练全流程&#…...
Unity中的transform.up
2025年6月8日,周日下午 在Unity中,transform.up是Transform组件的一个属性,表示游戏对象在世界空间中的“上”方向(Y轴正方向),且会随对象旋转动态变化。以下是关键点解析: 基本定义 transfor…...
