【Spring】Bean生命周期以及应用场景(注解版)

Spring中Bean的生命周期 applicationcontext的应用(实现国际化,事件的传递) 这个工程主要实现了: Spring中Bean的生命周期 applicationcontext的应用(实现国际化,事件的传递) 立即下载

前言

理清Spring容器管理Bean的过程有助于我们更好地根据需求制定更合理的设计方案,提升系统扩展性和执行效率。

Bean生命周期

下面通过简单的示例来理清Bean在Spring容器中的生命周期。

我们从整体到细节,首先是启动容器加载Bean,这是一个整体的过程。

/**
 * 测试 Spring Bean 生命周期
 * @author zyj
 */
public class LifeCycleTest {
    @Test
    public void testLifeCycle() {
        // 通过注解开启容器,并加载Bean
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GlobalConfig.class);
        // 关闭容器
        context.close();
    }
}

@Configuration
public class GlobalConfig {
    @Bean
    public Calculator calculator() {
        return new Calculator();
    }
    /**
     * @Order:加载到容器的优先级,越小代表优先级越高
     * @return
     */
    @Order(0)
    @Bean
    public FullyBeanPostProcessor fullyBeanPostProcessor() {
        return new FullyBeanPostProcessor();
    }
}

接着看看容器在加载Bean的时候都做了哪些处理。

我们需要对Bean加入Spring提供的接口,这些接口可以看做是给开发者干预加载Bean的过程的入口。

public class Calculator implements BeanNameAware, ApplicationContextAware {

    public Calculator() {
        System.out.println("<<<构造器执行>>>");
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("<<<BeanNameAware.setBeanName执行>>>");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("<<<ApplicationContextAware.setApplicationContext执行>>>");
    }

    @PostConstruct
    public void init() {
        System.out.println("<<<@PostConstruct执行>>>");
    }

	@PreDestroy
    public void destroy() {
        System.out.println("<<<@PreDestroy执行>>>");
    }
}

从代码可以看到这里有以下几个接口以及注解:

  • BeanNameAware:获取当前Bean在容器中的名字
  • ApplicationContextAware:为当前Bean注入容器
  • @PostConstruct:初始化方法(相当于Spring配置文件中的init-method、接口InitializingBean)
  • @PreDestroy:销毁方法(相当于Spring配置文件中的destroy-method、接口DisposableBean)

执行顺序

三月 06, 2020 3:09:52 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4f47d241: startup date [Fri Mar 06 15:09:52 CST 2020]; root of context hierarchy
三月 06, 2020 3:09:52 下午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'globalConfig' of type [class com.zyj.spring.config.GlobalConfig$$EnhancerBySpringCGLIB$$5aa1013d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

<<<构造器执行>>>
<<<BeanNameAware.setBeanName执行>>>
<<<ApplicationContextAware.setApplicationContext执行>>>
<<<BeanPostProcessor.postProcessBeforeInitialization执行>>>
<<<@PostConstruct执行>>>
<<<BeanPostProcessor.postProcessAfterInitialization执行>>>

三月 06, 2020 3:09:52 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4f47d241: startup date [Fri Mar 06 15:09:52 CST 2020]; root of context hierarchy

<<<@PreDestroy执行>>>

Process finished with exit code 0

细心的小伙伴肯定注意到了BeanPostProcessor的执行,我在Calculator中没有实现该接口,为什么加载的时候会打印呢?

一开始我理所应当地认为应该由每个Bean来实现BeanPostProcessor,这样就可以在@PostConstruct执行前后进行处理了。

但是我错了,验证的结果就是在加载当前Bean的时候并没有执行它所实现的BeanPostProcessor。

在找了一些资料之后,才了解BeanPostProcessor的用法。

请看上面的配置类,你可能漏掉了GlobalConfig中的FullyBeanPostProcessor。

public class FullyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Calculator) {
            System.out.println("<<<BeanPostProcessor.postProcessBeforeInitialization执行>>>");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Calculator) {
            System.out.println("<<<BeanPostProcessor.postProcessAfterInitialization执行>>>");
        }
        return bean;
    }
}

BeanPostProcessor由单独一个类来执行,统一由这个类来判断对哪些Bean执行哪些处理。

应用场景

ApplicationContextAware

作用:通过它,可以获取到Spring容器

应用场景:当实例并没有交给Spring管理时,我们就不能使用自动注入了。比如Utils使用Dao,这个时候就可以通过一个持有Spring容器的组件来获取Dao。

@Component
public class SpringJobBeanFactory implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
        
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringJobBeanFactory.applicationContext=applicationContext;    
    }
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
		if (applicationContext == null){
			return null;
		}
		return (T)applicationContext.getBean(name);
	}
}

使用:

TypeDao typeDao = SpringJobBeanFactory.getBean("typeDao");
Coursera | 离散数学概论(北大)| quiz答案 Coursera离散数学概论quiz答案Week1:数理逻辑:基本概念Week2:数理逻辑:命题逻辑及形式系统Week3:数理逻辑:谓词逻辑及形式系统Week4:集合论:集合代数   先放下Coursera上找的离散数学部分相关课程:   btw.线上学习拿证书还有很多,MOOC、edm等都可。   博主选了北京大学离散数学概论Discrete Mathematics Generality。Mooc上貌似也有,但是上课时间貌似不如Coursera灵活,Coursera时间自己调度,规定时间上完即可。目前课 阅读详情

相关推荐

【大模型】MHA,MQA,GQA及KV Cache详解

在自回归模型中(Autoregressive Models),模型会逐个生成文本的每个token,这个过程可能比较慢,因为模型一次只能生成一个token,而且每次新的预测都依赖于之前的上下文。这意味着,要预测第1000个token,你需要用到前999个token的信息,这通常涉及到对这些token的表示进行一系列矩阵乘法运算。而要预测第1001个token,你不仅需要前999个token的信息,还要加上第1000个token的信息。

酒酿小圆子呀~ 2612

Spring Bean生命周期,好像人的一生。。

Spring原来是一个社会,Bean就是身不由己的“社会人”……

三分恶的博客 3万+

图数据挖掘 ECC K-core core number truss number clique

K-core:什么叫k-core,给定一个正整数k(k>=0),k-core是一个G的最大子图(也就是说k-core是一个图的限制),将这个子图定义为Hk,对于Hk中的每个顶点v,他的度数都是大于等于k的。 k-core是内嵌的,如下图所示,集合{ABCD}是H3,也就是3-core的子图。而集合{ABCDE}是H2,也就是2-core的子图,集合{ABCDEGF}是H1,也就是1-core的子图,而从集合的角度来讲H3<H2<H1。 core number:什么叫kcor

weixin_45193103的博客 1684

Spring Bean的作用域和生命周期

Spring Bean的作用域 Spring 为Bean定义了5种作用域,分别为: singleton (单例) prototype (原型) request session global session singleton-单例模式(多线程下不安全) Spring loC容器中只会存在一 个共享的Bean实例,无论有多少个Bean引用它,始终指向同一个对象。 该模式在多线程下是不安全的。Singleton 作用域是Spring中的缺省作用域,也可以显示的将Bean定义为singleton模式 &l

张三李四王五老六 270

解决Qt平台插件初始化失败:This application failed to start because no Qt platform plugin could be initialized

本文深入解析了Qt应用程序启动时常见的‘platform plugin’初始化失败报错,指出其核心在于环境变量冲突或多版本Qt共存导致的插件路径混乱。文章提供了从环境变量检查、路径调整到文件补全的完整解决方案,并给出了使用windeployqt工具等预防性开发实践,帮助用户和开发者彻底解决这一经典问题。

weixin_29229261的博客 2176

COMSOL实战:薄膜声学超材料模态分析全流程解析(含预应力设置技巧)

本文详细解析了使用COMSOL进行薄膜声学超材料模态分析的全流程,包括预应力设置技巧和共振频率优化方法。通过实际案例和参数设置指南,帮助工程师掌握从几何建模到结果解读的关键步骤,特别适合声学超材料和共振薄膜结构的设计与优化。

ujm5678901的博客 292

Spring中Bean的生命周期(五步)(七步)(十步)

【代码】Spring中Bean的生命周期(五步)(七步)(十步)

refreshh的博客 2363

OpenHarmony自定义Launcher

OpenHarmony源码版本:4.0release开发板:DAYU / rk3568DevEco Studio版本:4.0.0.600切换分支为OpenHarmony-4.0-Release,并下载源码。

Abner_Crazy的博客 1629

Spring从零开始学使用系列(四)之@PostConstruct和@PreDestroy注解的使用

在Spring框架中,@PostConstruct和@PreDestroy注解是用于管理Bean生命周期的重要工具。这些注解提供了一种简洁的方式,在Bean的初始化和销毁阶段执行特定的逻辑,从而增强了应用程序的灵活性和可维护性。@PostConstruct注解用于在Bean初始化完成后立即执行特定的方法。这通常用于在依赖注入完成后进行一些初始化操作,例如分配资源或预填充缓存。@PreDestroy注解用于在Bean销毁之前执行特定的方法。

程序员LSP 1831

OKX 欧易 交易机器人开发基础

接口文档: https://www.okx.com/docs-v5/zh/#overview REST API 常用请求 查看账户余额 结果数据格式: 获取限价 结果格式: 获取指数行情 数据结构: 下单 结果数据: 获取未成交订单列表 返回结果: 撤单 结果结构:

Willin Wang 的全栈升级指南 2万+

【点云鸟瞰图BEV】点云鸟瞰图BEV原理与可视化

本节将介绍激光雷达等点云的鸟瞰图生成原理、代码及效果图。 1 BEV视图原理 点云BEV(Bird's Eye View)视图是指点云在垂直于高度方向的平面上的投影。通常,在获得bev视图前,会将空间分割成体素,利用体素对点云进行下采样,然后将每个体素作为一个点进行投影。体素是指将三维空间按照固定尺寸长方体进行划分时的长方体(Δl*Δw*Δh)。 体素投影时可以得到BEV视图的像素点坐标。每个像素点的特征取值则可以通过多种方式得到。 ...

叶子的博客 2万+

spring中bean的生命周期,及生命周期中的作用 和 作用域(单例 多例)

最近在看spring源码,所以总结下spring的生命周期和各个阶段的作用。 spring的生命周期概括起来主要如下: 实例化 属性注入 ioc注入 实现了BeanNameAware 则执行setBeanName方法 实现了BeanFactoryAware 则执行 setBeanFactory方法,p125 实现了ApplicationContextAware 执行setApplic...

进化的深山猿 9373

PCB仿真软件:Altium Designer_(15).AltiumDesigner的版本控制与项目管理

在进行PCB设计时,版本控制和项目管理是确保设计质量和团队协作效率的关键。Altium Designer 提供了强大的版本控制和项目管理功能,可以帮助设计团队更好地管理和维护项目。本节将详细介绍如何在Altium Designer中进行版本控制和项目管理,包括如何使用版本控制系统、如何管理项目文件、如何进行团队协作等。

kkchenjj的博客 1202

Spring Boot 注解探秘:Bean 管理的艺术

在 Spring Boot 应用开发中,Bean 的管理是核心功能之一。Spring Boot 提供了一套强大的注解系统,帮助开发者轻松管理 Bean 的生命周期和依赖注入。本文将深入探讨 Spring Boot 中常用的 Bean 处理注解及其应用场景。

weixin_45593273的博客 1572

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

spring bean生命周期

作用:方法级别的注解,注册一个bean到spring容器中。 用来@Configuration注解或@Component注解的类例。添加的bean的id为方法名 <bean> <bean id="defaultSampler" class="brave.sampler.Sampler.ALWAYS_SAMPLE"> </bean> /** * 配...

qq_43183527的博客 154

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【JavaEE】深入了解Spring中Bean的可见范围(作用域)以及前世今生(生命周期)

本文章主要讲解Spring中Bean的作用域和生命周期。作用域的一个例子,定义,六种不同的作用域,如何设置Bean的作用域。Spring的执行流程,生命周期,Bean的详细生命周期讲解,初始化过程讲解,代码演示...

Carefree_State的博客 2106

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

spring容器装配Bean基于注解

装配bean基于注解 注解:就是一个类,使用@注解名称 开发中:使用注解 取代 xml配置文件 @Component取代&lt;bean class=""&gt; @Component(“id”)取代&lt;bean id="" class=""&gt; web开发,提供3个@Component注解衍生注解(功能一样)取代&lt;bean class=""&gt; @Repo

qq_43650773的博客 78

【spring原理】Bean的作用域与生命周期

【spring原理】Bean的作用域与生命周期

yican2580的博客 1097

Spring 注解开发(六.Bean定义、作用范围以及生命周期)

注解开发定义bean 和纯注解开发配置文件。并在纯注解环境下实现bean生命周期设置

weixin_61620939的博客 358

第二章 Spring中的Bean

1、以下有关Bean的singleton作用域说法错误的是()。 A、prototype是Spring容器默认的作用域 B、对需要保持会话状态的Bean(如Struts2的Action类)应该使用prototype作用域 C、在使用prototype作用域时,Spring容器会为每个对该Bean的请求都创建一个新的实例 D、要将Bean定义为prototype作用域,只需在配置文件中将元素的scope属性值设置为prototype即可 参考答案 :A 2、以下有关Bean的装配方式说法正确的是()。 A、S

weixin_46066900的博客 8494

Bean作用域和生命周期

Spring中Bean对象的作用域和生命周期

m0_67683346的博客 604

【小家Spring】Spring注解驱动开发---Spring Ioc容器中Bean的生命周期详解(BeanPostProcessor解析)

前言 bean的生命周期指的是bean创建—初始化到销毁的过程。 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法 单实例:在容器启动的时候创建对象 多实例:容器不会管理这个bean;容器不会调用销毁方法; Bean生命周期初始化、销毁相关的4种方式 1、@Bean指定初始化方法和销毁方法 initMethod destroyMethod ...

架构师:通透,才能写出好代码! 2423

Spring中Bean的生命周期

在 Spring IoC 容器中,Bean 的生命周期是一个非常重要的概念,它定义了 Bean 从创建到销毁的完整过程。了解这一过程有助于开发者在合适的阶段对 Bean 进行定制化处理(如初始化资源、销毁资源等)。通过掌握 Bean 的生命周期,开发者可以更精准地控制 Bean 的行为,实现复杂的初始化逻辑和资源管理,提升 Spring 应用的健壮性和灵活性。

zty0721的博客 884

Spring框架中常用的注解

Spring框架中使用注解(Annotations)来简化配置过程,并提供更直观的方式来定义Bean、注入依赖以及配置其他组件。以下是一些常用的Spring注解及其应用场景 @ComponentScan Bean管理注解 @Component @Service, @Repository, @Controller @Autowired @Qualifier

Rubypyrrha的博客 1242

java中bean的作用域有哪些_详解Spring中Bean的生命周期和作用域及实现方式

前言在applicationContext.xml中配置完bean之后,Bean的声明周期状态有哪些。生命周期的各个阶段可以做什么。在applicationContext.xml配置bean的作用域有哪些。其中各个作用域代表的是什么。适用于什么情况。这篇文章做一个记录。生命周期初始化可以直接查看图片,图片来自Spring Bean Life Cycle从上图看出,Bean初始化完成包括9个步骤。其...

weixin_28844235的博客 298

【spring】@DependsOn注解学习

DependsOn是 Spring 框架中的一个注解,用于指定一个 bean 的依赖关系。当 Spring 容器初始化 bean 时,它会按照一定的顺序进行初始化。如果一个 bean 依赖于其他 bean,那么这个 bean 的初始化应该在依赖的 bean 之后进行。@DependsOn注解可以用于指定一个 bean 依赖于哪些 bean,这样 Spring 容器在初始化 bean 时,会先初始化依赖的 bean,然后再初始化当前 bean。

一个写了10年bug的程序员日常笔记。 2320
上一篇: 《Java并发编程实战》学习笔记(4)
下一篇: 缓存中间件与数据库的相爱相杀
章 鱼
博客等级 码龄10年 203粉丝 105原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值