对Spring PostConstruct注解的一点新认识

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

无论是Spring还是SpringBoot开发中,PostConstruct注解的使用频率还是比较高的,通常用于Bean初始化完成的一些动作。
在项目代码中,会将配置从配置中心中读取,然后初始化到指定的Bean中。其他需要动态获取配置的地方,直接依赖注入这个Bean即可。
示例代码如下:

ApplicationConfig

动态配置所在的类,主要是属性。

@Configuration
@Data
@Slf4j
public class ApplicationConfig {

  /**
     * client host
     */
  private String host;

  /**
     * client port
     */
  private String port;

  public ApplicationConfig() {
    log.info("ApplicationConfig constructor execute");
  }

  @PostConstruct
  public void init() {
    log.info("ApplicationConfig postConstructor execute");
  }
}

ApplicationConfigLoadService

从远程配置中心中获取配置信息,主要依赖PostConstruct方法。

@Service
@Slf4j
public class ApplicationConfigLoadService {

  @Resource
  private ApplicationConfig applicationConfig;

  public ApplicationConfigLoadService() {
    log.info("ApplicationConfigLoadService constructor execute");
  }

  @PostConstruct
  public void load() {
    log.info("ApplicationConfigLoadService postConstruct execute");
    // 可以是从数据库,或者远程的配置中心中读取配置
    String host = "127.0.0.1";
    String port = "8080";
    applicationConfig.setHost(host);
    applicationConfig.setPort(port);
  }
}

ApplicationClientFactory

使用ApplicationConfig,基于配置信息,在类初始化完成后,做一些动作。

@Component
@Slf4j
public class ApplicationClientFactory {

  @Resource
  private ApplicationConfig applicationConfig;

  public ApplicationClientFactory() {
    log.info("ApplicationClientFactory constructor execute");
  }

  @PostConstruct
  public void init() {
    log.info("ApplicationClientFactory postConstruct execute, host:{}, port:{}",
             applicationConfig.getHost(), applicationConfig.getPort());
  }
}

备注:

1.主要的类中,提供了一个无参的构造方法,以及一个使用了@PostConstructor注解的初始化方法,主要用于看一下执行顺序。
2.代码说明

  • ApplicationConfigLoadService 的初始化方法中加载配
  • ApplicationConfig的setter方法完成配置初始化
  • ApplicationClientFactory依赖ApplicationConfig中的属性完成一些初始化工作。

将上述代码执行一下,并查看日志。

2021-06-06 15:38:28.591  INFO 2790 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory constructor execute
2021-06-06 15:38:28.598  INFO 2790 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig constructor execute
2021-06-06 15:38:28.599  INFO 2790 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig postConstructor execute
2021-06-06 15:38:28.599  INFO 2790 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory postConstruct execute, host:null, port:null
2021-06-06 15:38:28.602  INFO 2790 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService constructor execute
2021-06-06 15:38:28.603  INFO 2790 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService postConstruct execut

可以看到ApplicationClientFactory的构造方法先被执行,然后由于依赖ApplicationConfig类,所以ApplicationConfig的构造方法和标识了PostConstruct注解的方法被执行,然后才会执行ApplicationClientFactory自己的postConstruct方法。
但是从日志中可以看出,此时由于ApplicationConfigLoadService还没被加载,所以读取到的配置都是空的。

尝试的解决方案

方案1:是可以采用DependsOn指定Bean的加载顺序。

修改代码如下:

value即为依赖Bean的名称。
@DependsOn(value = {"applicationConfigLoadService"})
@Component
@Slf4j
public class ApplicationClientFactory  
Beans on which the current bean depends. Any beans specified are guaranteed to be
created by the container before this bean. Used infrequently in cases where a bean
does not explicitly depend on another through properties or constructor arguments,
but rather depends on the side effects of another bean's initialization.

从JDK文档可以看出,DependsOn注解主要的使用场景是当前Bean没有显示通过属性或者构造参数依赖另外一个Bean,但是却要依赖另外一个Bean的一些初始化动作。
在上述代码示例中,通过添加DependsOn注解,可以解决问题。

2021-06-06 16:36:59.944  INFO 3688 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService constructor execute
2021-06-06 16:36:59.948  INFO 3688 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig constructor execute
2021-06-06 16:36:59.949  INFO 3688 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig postConstructor execute
2021-06-06 16:36:59.949  INFO 3688 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService postConstruct execute
2021-06-06 16:36:59.950  INFO 3688 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory constructor execute
2021-06-06 16:36:59.951  INFO 3688 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory postConstruct execute, host:127.0.0.1, port:8080

方案2: 显示通过@Resource或者@Autowired注入待依赖的Bean

在DependsOn的JDK代码中也可以看到,通过显示依赖可以解决问题。通过签名日志可以看出,当显示依赖注入某个Bean时,被注入Bean会依次执行对应的构造函数以及@PostConstructor注解的初始化方法。

public class ApplicationClientFactory {

  @Resource
  private ApplicationConfig applicationConfig;

  // 显示依赖
  @Resource
  private ApplicationConfigLoadService applicationConfigLoadService;

  public ApplicationClientFactory() {
    log.info("ApplicationClientFactory constructor execute");
  }

  @PostConstruct
  public void init() {
    log.info("ApplicationClientFactory postConstruct execute, host:{}, port:{}",
             applicationConfig.getHost(), applicationConfig.getPort());
  }
}

执行结果

2021-06-06 16:08:17.458  INFO 3286 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory constructor execute
2021-06-06 16:08:17.464  INFO 3286 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig constructor execute
2021-06-06 16:08:17.465  INFO 3286 --- [           main] c.y.m.configuration.ApplicationConfig    : ApplicationConfig postConstructor execute
2021-06-06 16:08:17.466  INFO 3286 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService constructor execute
2021-06-06 16:08:17.467  INFO 3286 --- [           main] c.y.m.c.ApplicationConfigLoadService     : ApplicationConfigLoadService postConstruct execute
2021-06-06 16:08:17.467  INFO 3286 --- [           main] c.y.m.c.ApplicationClientFactory         : ApplicationClientFactory postConstruct execute, host:127.0.0.1, port:8080

此时可以看到在ApplicationClientFactory的postConstruc中,依赖的ApplicationConfig是有对应属性值的。
但是,此处会存在一个风险问题,由于applicationConfigLoadService这个变量在当前类中并未实际使用,仅仅是为了依赖其postConstruct方法。对于后续维护的同学,很有可能无意将其移除。

Java高级架构面试知识点整理

我整理的《最全Java高级架构面试知识点整理》已升级为2.0版本,200个知识点,178页。点击这获取。同时欢迎来java架构交流群进行交流!!!

Spring纯注解开发上篇(包含Component、Configuration、ComponentScan、Scope、PostConstruct、PreDestroy注解) 注解开发定义bean顺序:" 1. 在所有需要放到容器中的类,在类上使用 @Component 注解 @Component("bookDao") public class BookDaoImpl implements BookDao {} @Component //如果没有指定id,则使用类名首字母小写做为id,即:bookServiceImpl public class BookServiceImpl implements BookService {............ 阅读详情

相关推荐

spring之PostConstruct使用

PostConstruct源码 package javax.annotation; import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; @Documented @Retention (RUNTIME) @Target(METHOD) public @interface PostCon.

Eflyings的博客 2944

java自带的注解@ PostConstruct

java注解@PostConstructor 1.spring项目加载数据字典 @PostConstruct注解的方法在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如数据字典之类的。 2.spring项目的定时任务 spring自带的@schedule,没有开关,项目启动总会启动一个线程; 做项目的时候就使用Java的timer,这个...

lixld的专栏 1742

Excel-MCP实战指南:零代码实现大模型与Excel的智能交互

本文详细介绍了Excel-MCP工具如何实现大模型与Excel的无缝交互,无需编写代码即可完成数据读写、图表生成等复杂操作。通过实战案例展示了Excel-MCP在销售报表自动化、财务对账等企业级场景中的应用,大幅提升工作效率。文章还提供了安装指南、核心功能解析和常见问题解决方案。

weixin_29212429的博客 432

深入理解Spring----PostConstruct和PreDestroy

一、PostConstruct 之前先来看一下Servlet的生命周期 Spring中有 Autowired Constructor PostConstrucotor Spring 会先通过初始化Bean对象,遍历类中的Field属性来看看有没有给被@Autowired修饰的,如果有就注入赋值,然后在执行被@PostCOnnstructor 修饰的方法 Constructor >> @Autowired >> @PostConstructor ...

qq_38345598的博客 583

Android7以上抓取https数据包-无需root

手机内装一个虚拟机,然后在虚拟机内运行我需要抓包的应用,该虚拟机内是不需要证书验证的。完美解决android7.0以上https无法抓包的问题。

qq_45764684的博客 1454

避坑指南:群晖DSM 7.X挂载NTFS硬盘,为什么你的SATA口不行?从原理到实战一次讲清

本文深入解析群晖DSM 7.X系统挂载NTFS硬盘的底层原理与实战排查方法,揭示SATA接口权限配置的关键参数(如esataportcfg和internalportcfg),并提供安全修改端口配置的详细步骤。针对不同型号群晖NAS的配置差异,给出替代方案与常见故障排查技巧,帮助用户解决NTFS硬盘挂载问题。

weixin_26757925的博客 256

Spring 注解面面通 之 @PostConstruct 应用解析以及与afterPropertiesSet、init-method对比

  简介   JSR-250规范为Bean初始化之后/销毁之前方法指定了两个注解:@PostConstruct和@PreDestroy,这两个注解可以应用在方法级别上,@PostConstruct注释方法在Bean实例化之后、应用注入之前调用,@PreDestroy注释方法在Bean实例销毁之前调用。   @PostConstruct和@PreDestroy规范中要去较为严格,但Spring在实现时,并未完全按照其规范实现,在Spring中应用@PostConstruct和@PreDestroy这两个注解,

键盘上流淌的日子 4373

用Stata复现经典文献:上市公司全要素生产率(TFP)计算全流程(含LP/OP代码解读)

本文提供了使用Stata软件复现上市公司全要素生产率(TFP)计算的完整实战指南。重点解读了主流的Levinsohn-Petrin(LP)和Olley-Pakes(OP)半参数估计方法,通过详细的数据清洗、变量构建与价格平减步骤,手把手演示了如何准确测算TFP,并强调了LP方法在处理中国上市公司数据时的稳定性和适用性。

b0c1d2的博客 589

postconstructor注解作用

如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

2201_75853118的博客 224

CentOS 7下Synopsys DC综合工具安装与配置全攻略(附常见报错解决方案)

本文详细介绍了在CentOS 7操作系统上安装与配置Synopsys Design Compiler(DC)综合工具的完整流程。内容涵盖从系统环境准备、软件安装、许可证配置到实战综合的全过程,并针对DC综合工具在安装和运行中常见的报错问题提供了具体的解决方案,帮助数字IC设计初学者快速搭建稳定的EDA学习环境。

weixin_29159441的博客 257

AS7262六通道可见光传感器:从光谱原理到物联网色彩检测实战

光谱检测是嵌入式感知领域的关键技术,其核心原理是通过特定波长的滤光片分离光线并转换为电信号,从而实现对环境光或物体反射光的成分分析。这项技术的价值在于将复杂的光学分析简化为可编程读取的数字信号,极大降低了色彩检测在物联网和智能设备中的应用门槛。在智能农业、工业分拣、环境监测等场景中,精确的光谱数据能够驱动自动化决策,例如评估植物光照条件或识别物料颜色。本文以Adafruit AS7262传感器为例,深入解析其基于硅干涉滤光片的六通道设计,并通过Arduino与Python实战,演示如何快速构建从数据采集到可

weixin_28738173的博客 595

PostConstruct注解解析

1、背景 想学习PostConstruct的注解的原因是在spring代码中犯了这样一个错误 @Component public class A{ @Autowired private B b; public static <T> T testB(String test) { b.method(); return test; } } 由于上边的testB方法是一个静态方法,所以可以直接调用A.testB,但是testB里边用到

Jarbein的博客(Java军师公众号) 2092

基于深度学习的时间序列预测

深度学习在时间序列数据中应用广泛,学术界已经有很多深度学习模型来适应不同领域的时间序列数据集的多样性。那么到底有哪些基于深度学习的时间序列预测模型?他们的优缺点是什么?让我们一起来看一下。

Sharon0408的博客 6580

Spring5.0--你的PostConstruct注解为什么不生效

PostConstruct注解依靠CommonAnnotationBeanPostProcessor的父类InitDestroyAnnotationBeanPostProcessor执行,当你启动注解功能<context:annotation-config/>会自动帮你注册CommonAnnotationBeanPostProcessor。 当bean初始化的时候(对应方法Abstra...

yeling3380222的博客 5773

Windows Docker + RK3588 部署 YOLO26-Pose 人体姿态检测

YOLO26-Pose 在 RK3588 上的部署流程是 Windows Docker 容器内 ONNX 导出 → RKNN 转换(INT8 量化)→ ADB 推送 → 板端 C++ 推理。YOLO26n-Pose 在 640 输入下全链路约 55 FPS,可以覆盖实时姿态检测需求。先在板端用单张图片验证关键点输出正确性,确认 C++ 后处理的解析逻辑无误后,再切换到摄像头实时推理。

m0_64661770的博客 98

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

探秘Spring(2)——PostConstruct注解工作原理解析

提示:本文的代码环境为SpringBoot2.3.4 文章目录前言一、PostConstruct是什么?二、可以做什么三、工作原理总结 前言 Spring已成为java开发web应用必会技术栈,本系列文章着重为大家揭秘spring中的技术点,本文重点介绍Bean实例化之后,依靠注解PostConstruct可以做的一些初始化的工作。 一、PostConstruct是什么? 从注解的全限定名(javax.annotation.PostConstruct)可以看出这个注解是JDK本身自带的注解,JDK中对

qq_20221431的博客 1623

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

spring PostConstruct 注解

摘要:@PostConstruct是JavaEE/JakartaEE提供的标准注解,用于在依赖注入完成后执行初始化逻辑,被Spring框架广泛支持。其执行时机固定(构造器→依赖注入→@PostConstruct),每个Bean仅允许一个无参void方法。优势包括依赖注入已完成、代码解耦、跨框架兼容性,但存在单次执行、异常敏感等局限。适用场景包括缓存预热、配置加载等初始化任务。 对比其他方式: 推荐场景:依赖注入后初始化用@PostConstruct,完全启动后逻辑用@EventListener(Applic

几十年资深高级架构师,技术专家的技术笔记。专注C、Java、Python、微服务、云原生、AI工程化及高并发系统分布式架构实战,分享源码剖析、性能调优与架构治理经验。 434

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Spring_注解

Spring_注解

底层码农 7881

Spring AOP注解通过 Autowired, Resource, Qualifier, PostConstruct

Spring AOP注解通过 Autowired, Resource, Qualifier, PostConstruct

hddyhg的博客 986

Spring中没有Resource、PostConstruct、PreDestroy注解

Spring中没有Resource、PostConstruct、PreDestroy注解 当我们使用Resource、PostConstruct、PreDestroy注解时会飘红报错,这是因为我们缺少相关的依赖包。 解决方案 Maven程序在pom.xml文件夹中加入对应依赖即可。 <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifac

weixin_44519237的博客 892

Spring原理揭秘--基于注解的注入

在之前的方法中我们知道spring是基于xml进行注入的bean,但是在目前的spring中我们一般不再是书写xml文件来一一列出需要管理的bean而是通过注解的方式来完成依赖的注入。下面我们就来聊聊依赖的注入是哪种方式。

qq_65779957的博客 1412

PostConstruct 注解:main 调用 spring 注入 service

实际作用 @PostContruct 是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。 @PostConstruct 是 Servlet 的注解,可以用来解决 main 方法调用 spring 注入的 service 类问题。 实例代码如下: @Autowired private Dao dao; public static void main(String[] args){ SpringApplication.run

BugAngel的博客 1338

PostConstruct 注解 配合 spring注解使用

在springmvc 中 配置加载缓存 需求:缓存的初始化是要在web项目启动的时候加载的, 用PostConstruct注解配合 被注解的方法的这个类也要被spring管理 因为 PostConstruct这个注解的方法会在 类的构造器执行完成后调用 所以需要spring管理这个类 那样就会在spring容器启动的时候 PostConstruct注解的方法

zr的博客 836

postconstruct注解_总是说spring难学?来看完这些spring的注解及其解释,真香

前言用过spring的人都知道,spring简单的通过注解就可以完成很多事情,但这些东西是如何实现的呢以及如何应用到我们自己的代码中?接下来,让我们一起开启注解的旅程。1. @Controller标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.@Controllerpublic class TestController { @Reque...

weixin_39717110的博客 119

PostConstruct注解不执行

通过PostConstruct注解进行初始化操作,可是怎么都不执行各种配置都配烂了,最终发现是default-lazy-init="true"的问题,惰性加载真的是用到的时候才初始化。在Bean上增加Lazy(false)解决...

zhengluu的专栏 5634
上一篇: 这个你得会,通过合理配置来支持百万级并发连接!!
普通网友
博客等级 码龄5年 1974粉丝 9原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值