Spring's @Bean annotation provides following optional elements to received lifecycle callbacks:
@Bean
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.annotation.Autowired; public class MyBean { private OtherBean otherBean; public MyBean() { System.out.println("MyBean constructor"); } public void myPostConstruct() { 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()"); } public void cleanUp() { 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(initMethod = "myPostConstruct", destroyMethod = "cleanUp") public MyBean myBean() { return new MyBean(); } @Bean public OtherBean otherBean() { return new OtherBean("Hello from otherBean!"); } 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 otherBean!'}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.