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&…...
编程语言的未来?
编程语言的未来? 随着科技的飞速发展,编程语言在计算机领域中扮演着至关重要的角色。它们是软件开发的核心,为程序员提供了与机器沟通的桥梁。那么,在技术不断进步的未来,编程语言的走向又将如何呢? 在技…...
在鸿蒙HarmonyOS 5中实现抖音风格的点赞功能
下面我将详细介绍如何使用HarmonyOS SDK在HarmonyOS 5中实现类似抖音的点赞功能,包括动画效果、数据同步和交互优化。 1. 基础点赞功能实现 1.1 创建数据模型 // VideoModel.ets export class VideoModel {id: string "";title: string ""…...

Day131 | 灵神 | 回溯算法 | 子集型 子集
Day131 | 灵神 | 回溯算法 | 子集型 子集 78.子集 78. 子集 - 力扣(LeetCode) 思路: 笔者写过很多次这道题了,不想写题解了,大家看灵神讲解吧 回溯算法套路①子集型回溯【基础算法精讲 14】_哔哩哔哩_bilibili 完…...

MODBUS TCP转CANopen 技术赋能高效协同作业
在现代工业自动化领域,MODBUS TCP和CANopen两种通讯协议因其稳定性和高效性被广泛应用于各种设备和系统中。而随着科技的不断进步,这两种通讯协议也正在被逐步融合,形成了一种新型的通讯方式——开疆智能MODBUS TCP转CANopen网关KJ-TCPC-CANP…...

2025盘古石杯决赛【手机取证】
前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来,实在找不到,希望有大佬教一下我。 还有就会议时间,我感觉不是图片时间,因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...

python执行测试用例,allure报乱码且未成功生成报告
allure执行测试用例时显示乱码:‘allure’ �����ڲ����ⲿ���Ҳ���ǿ�&am…...

RSS 2025|从说明书学习复杂机器人操作任务:NUS邵林团队提出全新机器人装配技能学习框架Manual2Skill
视觉语言模型(Vision-Language Models, VLMs),为真实环境中的机器人操作任务提供了极具潜力的解决方案。 尽管 VLMs 取得了显著进展,机器人仍难以胜任复杂的长时程任务(如家具装配),主要受限于人…...

Qemu arm操作系统开发环境
使用qemu虚拟arm硬件比较合适。 步骤如下: 安装qemu apt install qemu-system安装aarch64-none-elf-gcc 需要手动下载,下载地址:https://developer.arm.com/-/media/Files/downloads/gnu/13.2.rel1/binrel/arm-gnu-toolchain-13.2.rel1-x…...
LangFlow技术架构分析
🔧 LangFlow 的可视化技术栈 前端节点编辑器 底层框架:基于 (一个现代化的 React 节点绘图库) 功能: 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...
vue3 daterange正则踩坑
<el-form-item label"空置时间" prop"vacantTime"> <el-date-picker v-model"form.vacantTime" type"daterange" start-placeholder"开始日期" end-placeholder"结束日期" clearable :editable"fal…...

ubuntu系统文件误删(/lib/x86_64-linux-gnu/libc.so.6)修复方案 [成功解决]
报错信息:libc.so.6: cannot open shared object file: No such file or directory: #ls, ln, sudo...命令都不能用 error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory重启后报错信息&…...