当前位置: 首页 > news >正文

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文件中导入坐标&#xff1a; <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.29<…...

Character Controller Smooth

流畅的角色控制器 Unity的FPS解决方案&#xff01; 它是一种具有非常平滑运动和多种设置的解决方案&#xff1a; - 移动和跳跃 - 坐的能力 - 侧翻角度 - 不平整表面的处理 - 惯性守恒 - 重力 - 与物理物体的碰撞。 - 支持没有家长控制的平台 此解决方案适用于那些需要角色控制器…...

企业内训系统源码开发实战:搭建实践与经验分享

本篇文章中&#xff0c;小编将带领读者深入探讨企业内训系统的源码开发实战&#xff0c;分享在搭建过程中遇到的挑战与解决方案。 一、项目规划与需求分析 通过对企业内训需求的深入了解&#xff0c;我们可以更好地定义系统架构和数据库设计。 二、技术栈选择 在内训系统开发…...

15.三数之和(双指针,C解答附详细分析)

题目描述&#xff1a; 给你一个整数数组 nums &#xff0c;判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! j、i ! k 且 j ! k &#xff0c;同时还满足 nums[i] nums[j] nums[k] 0 。请 你返回所有和为 0 且不重复的三元组。 注意&#xff1a;答案中不可以包含…...

SpringCloud微服务 【实用篇】| Dockerfile自定义镜像、DockerCompose

目录 一&#xff1a;Dockerfile自定义镜像 1. 镜像结构 2. Dockerfile语法 3. 构建Java项目 二&#xff1a; Docker-Compose 1. 初识DockerCompose 2. 部署微服务集群 前些天突然发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;…...

Vue3+TS+ElementPlus的安装和使用教程【详细讲解】

前言 本文简单的介绍一下vue3框架的搭建和有关vue3技术栈的使用。通过本文学习我们可以自己独立搭建一个简单项目和vue3的实战。 随着前端的日月更新&#xff0c;技术的不断迭代提高&#xff0c;如今新vue项目首选用vue3 typescript vite pinia……模式。以前我们通常使用…...

浅析锂电池保护板(BMS)系统设计思路(四)SOC算法-扩展Kalman滤波算法

BMS开发板 1 SOC估算方法介绍 电池SOC的估算是电池管理系统的核心&#xff0c;自从动力电池出现以来&#xff0c;各种各样的电池SOC估算方法不断出现。随着电池管理系统的逐渐升级&#xff0c;电池SOC估算方法的效率与精度不断提高&#xff0c;下面将介绍常用几种电池SOC估算方…...

构建异步高并发服务器:Netty与Spring Boot的完美结合

前言 「作者主页」&#xff1a;雪碧有白泡泡 「个人网站」&#xff1a;雪碧的个人网站 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睡眠不管用怎么办&#xff0c;win11电脑睡眠功能失效了如何修复 在win11系统中拥有许多令人激动的新功能和改进&#xff0c;有些用户在使用win11电脑时可能会遇到一个问题&#xff1a;睡眠模式不起作用。当他们尝试将计算机置于睡眠状态时&#xff0c;却发现系统无法进…...

内坐标转换计算

前言 化学这边的库太多了。 cs这边的库太少了。 去看化学的库太累了。 写一个简单的实现思路&#xff0c;让cs的人能看懂。 向量夹角的范围 [0, pi) 这是合理的。 因为两个向量只能构成一个平面系统&#xff0c;平面系统内的夹角不能超过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&#xff0c;我只需要在一个编辑器中实用selenium java编写了一些脚本那么就会自动化了&#xff0c;是真的吗&#xff1f;答案肯定是假的。自动化肯定是需要做到真的完全自动化&#xff0c;那如何实现呢&#xff1f;接着往…...

python小工具之弱密码检测工具

一、引用的python模块 Crypto&#xff1a; Python中一个强大的加密模块&#xff0c;提供了许多常见的加密算法和工具。它建立在pyc.ypodome或pyc.ypto等底层加密库之上&#xff0c;为Python程序员提供了简单易用的API&#xff0c;使其可以轻松地实现各种加密功能。 commands…...

链接器--动态链接器--延迟绑定与动态链接器是什么?学习笔记二

内容在下面链接&#xff08;通过新建标签页打开&#xff09;&#xff1a; 链接器--动态链接器--延迟绑定与动态链接器是什么&#xff1f;学习笔记二一个例子来看延迟加载https://mp.weixin.qq.com/s?__bizMzkyNzYzMjMzNA&mid2247483713&idx1&snee90a5a7d59872287…...

JMeter CSV 参数文件的使用方法

.在 JMeter 测试中&#xff0c;参数化是非常重要的&#xff0c;参数化允许我们模拟真实世界中的各种情况。本文我们将探讨如何在 JMeter 中使用 CSV 参数文件。 创建 CSV 文件 首先&#xff0c;我们需要创建一个逗号分隔的值&#xff08;CSV&#xff09;文件&#xff0c;其中…...

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设计模式之六大设计原则

前言&#xff1a;听说有本很牛的关于Java设计模式的书——重学Java设计模式&#xff0c;然后买了(*^▽^*) 开始跟着小傅哥学Java设计模式吧&#xff0c;本文主要记录笔者的学习笔记和心得。 打卡&#xff01;打卡&#xff01; 六大设计原则 &#xff08;引读&#xff1a;这里…...

数据结构:第7章:查找(复习)

目录 顺序查找&#xff1a; 折半查找&#xff1a; 二叉排序树&#xff1a; 4. (程序题) 平衡二叉树&#xff1a; 顺序查找&#xff1a; ASL 折半查找&#xff1a; 这里 j 表示 二叉查找树的第 j 层 二叉排序树&#xff1a; 二叉排序树&#xff08;Binary Search Tree&…...

编程语言的未来?

编程语言的未来&#xff1f; 随着科技的飞速发展&#xff0c;编程语言在计算机领域中扮演着至关重要的角色。它们是软件开发的核心&#xff0c;为程序员提供了与机器沟通的桥梁。那么&#xff0c;在技术不断进步的未来&#xff0c;编程语言的走向又将如何呢&#xff1f; 在技…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

线程同步:确保多线程程序的安全与高效!

全文目录&#xff1a; 开篇语前序前言第一部分&#xff1a;线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分&#xff1a;synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分&#xff…...

vscode(仍待补充)

写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh&#xff1f; debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

关于 WASM:1. WASM 基础原理

一、WASM 简介 1.1 WebAssembly 是什么&#xff1f; WebAssembly&#xff08;WASM&#xff09; 是一种能在现代浏览器中高效运行的二进制指令格式&#xff0c;它不是传统的编程语言&#xff0c;而是一种 低级字节码格式&#xff0c;可由高级语言&#xff08;如 C、C、Rust&am…...

智能分布式爬虫的数据处理流水线优化:基于深度强化学习的数据质量控制

在数字化浪潮席卷全球的今天&#xff0c;数据已成为企业和研究机构的核心资产。智能分布式爬虫作为高效的数据采集工具&#xff0c;在大规模数据获取中发挥着关键作用。然而&#xff0c;传统的数据处理流水线在面对复杂多变的网络环境和海量异构数据时&#xff0c;常出现数据质…...

python执行测试用例,allure报乱码且未成功生成报告

allure执行测试用例时显示乱码&#xff1a;‘allure’ &#xfffd;&#xfffd;&#xfffd;&#xfffd;&#xfffd;ڲ&#xfffd;&#xfffd;&#xfffd;&#xfffd;ⲿ&#xfffd;&#xfffd;&#xfffd;Ҳ&#xfffd;&#xfffd;&#xfffd;ǿ&#xfffd;&am…...

Java求职者面试指南:计算机基础与源码原理深度解析

Java求职者面试指南&#xff1a;计算机基础与源码原理深度解析 第一轮提问&#xff1a;基础概念问题 1. 请解释什么是进程和线程的区别&#xff1f; 面试官&#xff1a;进程是程序的一次执行过程&#xff0c;是系统进行资源分配和调度的基本单位&#xff1b;而线程是进程中的…...

比较数据迁移后MySQL数据库和OceanBase数据仓库中的表

设计一个MySQL数据库和OceanBase数据仓库的表数据比较的详细程序流程,两张表是相同的结构,都有整型主键id字段,需要每次从数据库分批取得2000条数据,用于比较,比较操作的同时可以再取2000条数据,等上一次比较完成之后,开始比较,直到比较完所有的数据。比较操作需要比较…...

上位机开发过程中的设计模式体会(1):工厂方法模式、单例模式和生成器模式

简介 在我的 QT/C 开发工作中&#xff0c;合理运用设计模式极大地提高了代码的可维护性和可扩展性。本文将分享我在实际项目中应用的三种创造型模式&#xff1a;工厂方法模式、单例模式和生成器模式。 1. 工厂模式 (Factory Pattern) 应用场景 在我的 QT 项目中曾经有一个需…...

医疗AI模型可解释性编程研究:基于SHAP、LIME与Anchor

1 医疗树模型与可解释人工智能基础 医疗领域的人工智能应用正迅速从理论研究转向临床实践,在这一过程中,模型可解释性已成为确保AI系统被医疗专业人员接受和信任的关键因素。基于树模型的集成算法(如RandomForest、XGBoost、LightGBM)因其卓越的预测性能和相对良好的解释性…...