The interface InitializingBean has one method afterPropertiesSet which is called by spring framework after it has set all bean properties.
InitializingBean
afterPropertiesSet
The interface DisposableBean has one method destroy which is called by spring framework when JVM sends the shutdown signal.
DisposableBean
destroy
package com.logicbig.example; public class OtherBean { private String message; public OtherBean(String message) { this.message = message; } @Override public String toString() { return "OtherBean{" + "message='" + message + '\'' + '}'; } }
package com.logicbig.example; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; public class MyBean implements InitializingBean, DisposableBean { private OtherBean otherBean; public MyBean() { System.out.println("MyBean constructor"); } @Override public void afterPropertiesSet() { System.out.println("myPostConstruct()"); } @Autowired public void setOtherBean(OtherBean otherBean) { System.out.println("setOtherBean(): " + otherBean); this.otherBean = otherBean; } public void doSomething() { System.out.println("doSomething()"); } @Override public void destroy() { System.out.println("cleanUp method"); } }
package com.logicbig.example; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LifeCycleExample { @Bean public MyBean myBean() { return new MyBean(); } @Bean public OtherBean otherBean() { return new OtherBean("Hello from other Bean"); } public static void main(String[] args) { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleExample.class); context.registerShutdownHook(); System.out.println("-- accessing bean --"); MyBean bean = context.getBean(MyBean.class); bean.doSomething(); System.out.println("-- finished --"); } }
MyBean constructorsetOtherBean(): OtherBean{message='Hello from other Bean'}myPostConstruct()-- accessing bean --doSomething()-- finished --cleanUp method
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.