spring-boot - SpringBoot bean 生命周期管理
问题描述
我正在学习 springboot 应用程序中由 ApplicationContext 管理的 bean 的初始化和销毁回调。我有一个实现 InitializingBeans 和 DisposableBeans 接口的 bean。我确实有一个被调用的 @PostConstruct。但是,当我删除实现时,我没有看到调用的 init 方法。我错过了什么?
@Component
public class LifeCycleBean implements InitializingBean, DisposableBeans{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LifeCycleBean() {
// TODO Auto-generated constructor stub
System.out.println("Learning lifecycle - COnstructor invoked"+name);
}
@Override
public void destroy() throws Exception {
System.out.println("Learning lifecycle - Calling Destroy Method");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("Learning lifecycle - afterPropertiesSet
invoked"+name);
}
//This never got executed
public void init() {
System.out.println("Learning lifecycle - initMethod invoked"+name);
}
@PostConstruct
public void postConstructMethod() {
System.out.println("Learning lifecycle - postConstructMethod
invoked"+name);
}
@PreDestroy
public void preDestroyMethod() {
System.out.println("Learning lifecycle - preDestroyMethod invoked"+name);
}
}
SpringBoot应用程序
@SpringBootApplication
public class LifeCycleApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(LifeCycleApplication.class, args);
System.out.println("going to get bean definition names");
ctx.getBeanDefinitionNames();
LifeCycleBean bean = ctx.getBean(LifeCycleBean.class);
System.out.println("before setting name");
bean.setName("bean");
System.out.println("after setting name");
}
}
我如何以及何时看到 springboot 应用程序中调用的 init 方法?
解决方案
推荐阅读
- mongodb - 在 PSA 设置中的 oplog 中查找数据修改条目
- spring-boot - JSON解析错误:无法构造无字符串参数构造函数/工厂方法的实例以从字符串值(“名称”)反序列化
- ansible - ansible authorized_key 模块覆盖原始文件
- applepay - 如何在 Shopify 网站上自定义苹果支付按钮和谷歌支付按钮样式
- angular - SpringCloud Dataflow Keycloak Angular 8集成 - 401未经授权(有时(?))
- java - 如何直接从 Uni 返回一个值
无需将其转换为 CompletableFuture - javascript - TypeError:无法读取 null 的属性 'foo' - Object,React
- javascript - 如何使用标头、有效负载和正文制作 httpclient 获取请求?角度 API
- python - Pygame(我正在尝试为我的课程制作一个与 agar.io 非常相似的游戏)我怎样才能让它让背景移动
- c - 将平台设置为 WIN32,以便在 Visual Studio 2019 中从命令行编译 C 代码