【超详细的SpringBoot笔记】详解获取bean的三种方式

@PostConstruct注解详细分析,结合案例和使用场景(保姆级教程) juc、java 阅读详情

在使用spring框架中我们都知道,某个类如果使用了@Service、@Autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,只有通过spring的IOC容重中获取这个类的实例时,那些被依赖的对象才能正确被初始化,否则那些被依赖的对象都是null。 

所以就有一个问题,在普通类中如何获取spring ioc容器中的bean(spring 托管的bean)。

我们都知道,在spring中ApplicationContext这个上下文对象是获取bean的基础。

在spring boot中,我们可以通过下面的三种方式来获取Bean。

相关springboot学习视频:

https://www.bilibili.com/video/BV1XQ4y1m7ex

第一种方式

注解@PostConstruct

PostConstruct 注释用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化。此方法必须在将类放入服务之前调用。

支持依赖关系注入的所有类都必须支持此注释。即使类没有请求注入任何资源,用 PostConstruct 注释的方法也必须被调用。只有一个方法可以用此注释进行注释。

应用 PostConstruct 注释的方法必须遵守以下所有标准:

  • 该方法不得有任何参数,除非是在 EJB 拦截器 (interceptor) 的情况下,根据 EJB 规范的定义,在这种情况下它将带有一个 InvocationContext 对象 ;
  • 该方法的返回类型必须为 void;
  • 该方法不得抛出已检查异常;
  • 应用 PostConstruct 的方法可以是 public、protected、package private 或 private;
  • 除了应用程序客户端之外,该方法不能是 static;
  • 该方法可以是 final;
  • 如果该方法抛出未检查异常,那么不得将类放入服务中,除非是能够处理异常并可从中恢复的 EJB。

第二种方式

启动类ApplicationContext

实现方式:在springboot的启动类中,定义static变量ApplicationContext,利用容器的getBean方法获得依赖对象。推荐一个 Spring Boot 基础教程及实战示例:https://github.com/javastacks/javastack

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
 * @author: clx
 * @version: 1.1.0
 */
@SpringBootApplication
public class Application {
    public static ConfigurableApplicationContext ac;
    public static void main(String[] args) {
       ac = SpringApplication.run(Application.class, args);
    }
 
}

调用方式

/**
 * @author: clx
 * @version: 1.1.0
 */
@RestController
public class TestController {
    /**
     * 方式二
     */
    @GetMapping("test2")
    public void method_2() {
        AutoMethodDemoService methodDemoService = Application.ac.getBean(AutoMethodDemoService.class);
        String test2 = methodDemoService.test2();
        System.out.println(test2);
    }
}

第三种方式

手动注入ApplicationContext

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
 
/**
 * springboot静态方法获取 bean 的三种方式(三)
 * @author: clx
 * @version: 1.1.0
 */
@Component
public class StaticMethodGetBean_3<T> implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        StaticMethodGetBean_3.applicationContext = applicationContext;
    }
 
    public static <T> T  getBean(Class<T> clazz) {
        return applicationContext != null?applicationContext.getBean(clazz):null;
    }
}

调用方式

/**
 * 方式三
 */
@Test
public void method_3() {
    AutoMethodDemoService autoMethodDemoService = StaticMethodGetBean_3.getBean(AutoMethodDemoService.class);
    String test3 = autoMethodDemoService.test3();
    System.out.println(test3);
}

以上三种方式楼主都测试过可以为完美使用。

Spring 中获取 Bean 对象的三种方式 获取 Bean 对象的几种方式 阅读详情

相关推荐

PostConstruct注解详细使用说明及理解

@PostConstruct注解: 该注解是Java jdk提供的注解,而不是Spring框架提供的, JavaEE5引入了@PostConstruct和@PreDestroy两个作用于Servlet生命周期的注解,实现Bean初始化之前和销毁之前的自定义操作。 该注解的方法在整个Bean初始化中的执行顺序: Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的初始化方法) 官方文档:https://docs.ora.

skh2015java的博客 5万+

@PostConstruct注解,你该好好看看

在最近的工作中,get到一个很实用的注解,分享给诸位。 痛点 做过微信或支付宝支付的童鞋,可能遇到过这种问题,就是填写支付结果回调,就是在支付成功之后,支付宝要根据我们给的地址给我们进行通知,通知我们用户是否支付成功,如果成功我们就要去处理下面相应的业务逻辑,如果在测试服务,那么这个回调地址我们就需要填写测试服务的,如果发布到线上那么我们就需要改成线上的地址。 针对上面的场景,我们一般都会通...

一个程序员的成长 6151

钣金件设计规范

为保证折弯 强度,钣金折弯钣金应大于材料的最小折弯半径。在设计U型弯曲件时,两弯曲边最好长度相等,以免弯曲时产品偏 移而产生废品,如果因为结构设计不允许两边一样长,为保证产品在模 具中准确定位,应预先在设计时添加工艺定位孔,特别是多次折弯成 形的零件,必须设计工艺孔为定位基准,以减少累计误差,保证产品 质量,如图2-11所示。凸包是依靠材料的延伸使钣金件形成局部凹陷或凸起的冲压工序凸包与拉深是完全不同的冲压工艺,凸包中材料厚度的改变为费意图性 的,即厚度的少量改变是变形过程中形成的,不是设计指定的要求。

制冷技术咨询与服务的博客 7327

Java spring 注解 @PostConstruct 实战讲解

@PostConstruct 可以在Servlet初始化之前加载一些缓存数据,如:预热数据字典,读取properties配置文件

Java Punk 2万+

块坐标下降法实战:如何用Python一步步优化无人机通信网络?

本文通过Python实战案例,详细介绍了块坐标下降法在优化无人机通信网络中的应用。文章以最大化网络吞吐量为目标,将复杂的非凸问题拆解为功率分配和轨迹规划两个子问题,并提供了完整的算法实现、代码示例及调参指南,为机器学习工程师解决类似优化问题提供了实用参考。

sat99的博客 975

SAP开发实战:用FI_DOCUMENT_CHANGE BAPI批量修改FB03凭证抬头和行项目文本(附完整ABAP代码)

本文详细介绍了如何使用SAP的FI_DOCUMENT_CHANGE BAPI批量修改FB03凭证抬头和行项目文本,提供完整的ABAP代码实现方案。通过该BAPI,开发者可以高效完成财务凭证的批量修改,确保数据一致性和审计合规性,显著提升SAP财务模块的运维效率。

weixin_29224589的博客 381

SpringBoot学习笔记,获取Spring Bean的三种方式

在使用spring框架中我们都知道,某个类如果使用了@Service、@Autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,只有通过spring的IOC容重中获取这个类的实例时,那些被依赖的对象才能正确被初始化,否则那些被依赖的对象都是null。 所以就有一个问题,在普通类中如何获取spring ioc容器中的bean(spring 托管的bean)。 我们都知道,在spring中ApplicationContext这个上下文对象是获取bean的基础。在spring boot中,我们可以

f5465245的博客 612

C# 上位机程序中的数据采集与存储技术:从采集到持久化的完整解决方案

本文系统讲解C#上位机程序如何实现设备数据采集与持久化。主要内容包括:1)多种数据采集方式(串口通信、Modbus、OPC等)及代码示例;2)详细对比不同存储技术(CSV、SQLite、关系型数据库等)的优缺点;3)提供SQLite等存储实现代码;4)推荐分层系统架构(采集-缓存-存储-可视化);5)性能优化建议(多线程采集、异步存储、批量写入等)。文章强调应根据项目需求选择合适的技术方案,构建高效稳定的数据采集存储闭环系统。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1025

SpringBoot 笔记

草稿箱里不知道什么时候的笔记。

yesyesyes_yes的博客 441

基于YOLO系列的安全帽检测系统:从理论到实现的完整指南

安全帽检测作为计算机视觉在工业安全领域的重要应用,近年来得到了广泛关注。本文详细介绍了基于YOLOv5、YOLOv6、YOLOv7和YOLOv8的安全帽检测系统的完整实现方案,包括算法原理、数据集构建、模型训练、性能优化以及完整的UI界面设计。通过对比分析不同YOLO版本的性能差异,本文为工业安全检测系统的开发提供了全面的技术参考和实践指导。

YOLO 364

STM32G0/G4无刷电机硬件设计与FOC控制实现

无刷直流电机(BLDC)和永磁同步电机(PMSM)的矢量控制依赖于高精度电流采样、实时SVPWM调制与闭环PI调节等核心技术。其底层实现需兼顾电机本体建模、坐标变换(Clark/Park)、死区补偿及硬件资源约束。STM32G0系列凭借CORDIC协处理器与超低功耗特性,适用于成本敏感型有感FOC应用;而STM32G4集成运放、FMAC滤波器与高级定时器,可支撑高性能无感控制与多源传感融合。该技术广泛应用于机器人关节、智能云台、伺服驱动等场景,是嵌入式电机控制工程师必须掌握的工程化落地能力。

weixin_35751412的博客 121

【SpringBoot篇】详解Bean的管理(获取bean,bean的作用域,第三方bean)

在项目中,我们自定义一个类,如果我们想把这个类交给ioc容器管理,加上@Component衍生注解即可如果这个类不是我们自己自定义的,是我们引入第三方依赖中的,而且我们还想把这个类交给ioc容器管理,那么我们应该定义一个方法,在这个方法上加上@Bean在技术的道路上,我们不断探索、不断前行,不断面对挑战、不断突破自我。科技的发展改变着世界,而我们作为技术人员,也在这个过程中书写着自己的篇章。让我们携手并进,共同努力,开创美好的未来!愿我们在科技的征途上不断奋进,创造出更加美好、更加智能的明天!

小吉妙妙屋 5209

YOLOv8 眼底病变检测(眼底照片)详细说明

本文介绍了基于YOLOv8的眼底病变自动检测系统。该系统可识别糖尿病视网膜病变、青光眼等5类常见眼底病变,包括微动脉瘤、出血点等特征。核心技术包含图像预处理、模型训练、病变检测与量化分析三个模块,采用1024×1024高分辨率输入,针对医学图像特点优化数据增强策略。系统支持批量处理、可视化标注和临床报告生成,提供病变数量、面积密度和严重程度评分等量化指标。特别强调医学合规性要求,需专业医生参与数据标注和模型验证,符合医疗器械认证标准。该系统可作为眼科医生的辅助诊断工具,提高眼底病变筛查效率。

u010117029的博客 133

SpringBoot静态方法获取 bean的三种方式

注意: 调用者要被spring管理 方式一 注解@PostConstruct import com.example.javautilsproject.service.AutoMethodDemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework...

Chilx的博客 2万+

TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate

这篇被 ICLR 2026 接收的论文提出了一种名为TurboQuant的全新在线向量量化(Vector Quantization, VQ)算法。该研究的核心目标是解决大语言模型(LLM)在长上下文推理时面临的 KV Cache 显存消耗瓶颈,以及大规模向量数据库在近似最近邻检索中的存储与延迟问题。有别于现有技术,TurboQuant 是一种无需任何校准数据、无需训练的在线算法(Data-oblivious)。

c_cpp_csharp的专栏 118

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

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

SpringBoot中获取Bean的三种方式

在使用spring框架中我们都知道,某个类如果使用了@Service、@Autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,只有通过spring的IOC容重中获取这个类的实例时,那些被依赖的对象才能正确被初始化,否则那些被依赖的对象都是null。 所以就有一个问题,在普通类中如何获取spring ioc容器中的bean(spring 托管的bean)。 我们都知道,在spring中ApplicationContext这个上下文对象是获取bean的基础。在spring boot中,我们可.

DDDYSz的博客 9330

深度学习工具包 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")

SpringBoot中获取ApplicationContext的三种方式

SpringBoot中获取ApplicationContext的三种方式 ApplicationContext是什么? 简单来说就是Spring中的容器,可以用来获取容器中的各种bean组件,注册监听事件,加载资源文件等功能。 Application Context获取的几种方式 1 直接使用Autowired注入 @Component public class Book1 { @Aut...

. 5万+

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

SpringBoot获取bean的几种方式

ApplicationObjectSupport类图入下,我们看到它实现了ApplicationContextAware接口,在Spring容器初始化过程中回调方法setApplicationContext来完成ApplicationContext的赋值。通过实现ApplicationContextAware接口,在Spring容器启动时将ApplicationContext注入进去,从而获取ApplicationContext对象,这种方法也是常见的获取Bean的一种方式,推荐使用。

hk000001的博客 5171

SpringBoot静态方法获取 bean 的三种方式

包含最全MySQL、Redis、Java并发编程等等面试题和答案,用于参考~

Y1567409的博客 2861

Spring Boot获取Bean的三种方式

这些方式各有优势,选择哪一种取决于具体的应用场景和需求。通过BeanFactory的方式适合轻量级应用和移动设备,而BeanFactoryAware和ApplicationContext则更适合需要完整Spring功能的场合。

2301_76419561的博客 4526
上一篇: Spring中的相关配置,还有谁不知道?
下一篇: 深入解读SpringBoot是什么?它到底有什么用?
Java_Coding1
博客等级 码龄5年 9粉丝 46原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值