SpringBoot bean生命周期管理

时间:2019-07-21 21:54:06

标签: spring-boot

我正在学习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);
}
}

SpringBootApplication

@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方法?

0 个答案:

没有答案