Often, in enterprise application development, developers will want to plug in some extra functionality to be executed just after the construction and before the destruction of a business service. Spring provides multiple methods for interacting with such stages in the life cycle of a bean.
The Spring IoC container invokes the callback methods afterPropertiesSet()
of org.springframework.beans.factory.InitializingBean
and destroy()
of org.springframework.beans.factory.DisposableBean
on any Spring bean and implements them:
public class UserServiceImpl implements UserService, InitializingBean, DisposableBean { ... @Override public void afterPropertiesSet() throws Exception { logger.debug(this + ".afterPropertiesSet() invoked!"); // Your initialization code goes here.. } @Override public void destroy() throws Exception { logger.debug(this + ".destroy() invoked!"); // Your cleanup code goes here.. } ... }
Spring supports JSR 250 @PostConstruct
and @PreDestroy
annotations on any Spring bean in an annotation-supported environment, as shown here. Spring encourages this approach over implementing Spring-specific interfaces, as given in the previous section:
@Service public class AnnotatedTaskService implements TaskService { ... @PostConstruct public void init() { logger.debug(this.getClass().getName() + " started!"); } @PreDestroy public void cleanup() { logger.debug(this.getClass().getName() + " is about to destroy!"); } ... }