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&…...
编程语言的未来?
编程语言的未来? 随着科技的飞速发展,编程语言在计算机领域中扮演着至关重要的角色。它们是软件开发的核心,为程序员提供了与机器沟通的桥梁。那么,在技术不断进步的未来,编程语言的走向又将如何呢? 在技…...
(十)学生端搭建
本次旨在将之前的已完成的部分功能进行拼装到学生端,同时完善学生端的构建。本次工作主要包括: 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...
linux 错误码总结
1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...
Cinnamon修改面板小工具图标
Cinnamon开始菜单-CSDN博客 设置模块都是做好的,比GNOME简单得多! 在 applet.js 里增加 const Settings imports.ui.settings;this.settings new Settings.AppletSettings(this, HTYMenusonichy, instance_id); this.settings.bind(menu-icon, menu…...
Mobile ALOHA全身模仿学习
一、题目 Mobile ALOHA:通过低成本全身远程操作学习双手移动操作 传统模仿学习(Imitation Learning)缺点:聚焦与桌面操作,缺乏通用任务所需的移动性和灵活性 本论文优点:(1)在ALOHA…...
招商蛇口 | 执笔CID,启幕低密生活新境
作为中国城市生长的力量,招商蛇口以“美好生活承载者”为使命,深耕全球111座城市,以央企担当匠造时代理想人居。从深圳湾的开拓基因到西安高新CID的战略落子,招商蛇口始终与城市发展同频共振,以建筑诠释对土地与生活的…...
Python竞赛环境搭建全攻略
Python环境搭建竞赛技术文章大纲 竞赛背景与意义 竞赛的目的与价值Python在竞赛中的应用场景环境搭建对竞赛效率的影响 竞赛环境需求分析 常见竞赛类型(算法、数据分析、机器学习等)不同竞赛对Python版本及库的要求硬件与操作系统的兼容性问题 Pyth…...
第一篇:Liunx环境下搭建PaddlePaddle 3.0基础环境(Liunx Centos8.5安装Python3.10+pip3.10)
第一篇:Liunx环境下搭建PaddlePaddle 3.0基础环境(Liunx Centos8.5安装Python3.10pip3.10) 一:前言二:安装编译依赖二:安装Python3.10三:安装PIP3.10四:安装Paddlepaddle基础框架4.1…...
Python训练营-Day26-函数专题1:函数定义与参数
题目1:计算圆的面积 任务: 编写一个名为 calculate_circle_area 的函数,该函数接收圆的半径 radius 作为参数,并返回圆的面积。圆的面积 π * radius (可以使用 math.pi 作为 π 的值)要求:函数接收一个位置参数 radi…...
在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/v2@v2.2.0 更换为 go-ansible/@v1.1.7
在 Go 项目中降级 go-ansible 从 v2.2.0 到 v1.1.7 具体步骤: 第一步: 修改 go.mod 文件 // 原 v2 版本声明 require github.com/apenella/go-ansible/v2 v2.2.0 替换为: // 改为 v…...
起重机起升机构的安全装置有哪些?
起重机起升机构的安全装置是保障吊装作业安全的关键部件,主要用于防止超载、失控、断绳等危险情况。以下是常见的安全装置及其功能和原理: 一、超载保护装置(核心安全装置) 1. 起重量限制器 功能:实时监测起升载荷&a…...
