Bean Lifecycle: @PostConstruct and @PreDestroy
Explore the lifecycle of Spring beans by understanding how to use @PostConstruct to perform initialization after dependencies are set and @PreDestroy to handle cleanup before bean destruction. This lesson helps you learn how to implement custom initialization and cleanup logic using logging to track bean creation and removal within a Spring application.
We'll cover the following...
Spring manages the entire lifecycle of beans from the time they are created till the time they are destroyed. It provides post-initialization and pre-destruction callback methods on the beans. The developer can tap into these callbacks and write custom initialization and cleanup code.
For the code example shown in this lesson, we have created a sub-package called lesson11 inside the package io.datajek.spring.basics.movierecommendersystem. The package contains MovieRecommenderSystemApplication.java, Filter.java, ContentBasedFilter.java, and RecommenderImplementation.java files.
In this lesson, we will introduce the slf4j logger to log the sequence of events in our application and use it instead of System.out.println. Loggers offer flexibility, as well as better output, that includes ...