首页 > 解决方案 > 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 方法?

标签: spring-boot

解决方案


推荐阅读