1

I am learning the initialization and destruction callbacks for a bean managed by ApplicationContext in a springboot application. I have a bean which implements InitializingBeans and DisposableBeans interfaces.I do have a @PostConstruct which gets invoked. However I am not seeing the init method invoked when i remove the implementation.What am i missing?

@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");
}
}

How and when do i see the init method invoked in springboot application?

mack
  • 345
  • 5
  • 18
  • why would you? is it a part of some interface? – Antoniossss Jul 21 '19 at 22:11
  • It makes sense!.. But i am just trying to correlate how the init-methods in the traditional XML way of spring initialization would relate to a Spring boot application. Is it possible to specify a init-method explicitly for spring boot applications? Or i should only rely on @PostConstruct annotations? – mack Jul 21 '19 at 22:13
  • Possible duplicate of https://stackoverflow.com/questions/8519187/spring-postconstruct-vs-init-method-attribute basically, without xml config, @PostConstruct is the replacement for init-method, even though they are slightly different. – Gabriel Robaina Jul 22 '19 at 02:07
  • Gabriel - I do agree the questions are in similar terms to the link provided but I wanted to understan the "slight difference" that you are referring to. Even the post does not articulate much on that part or I am not able to appreciate the subtle difference. Can you please expplain? – mack Jul 22 '19 at 02:39

0 Answers0