Java Reference
In-Depth Information
The following list shows the steps through which the Spring IoC container manages the life cycle of
a bean (this list will be expanded as more features of the IoC container are introduced):
1. Create the bean instance either by a constructor or by a factory method (a
static method or a method on a bean instance).
2. Set the values and bean references to the bean properties.
3. Call the initialization callback methods.
4. The bean is ready to be used.
5. When the container is shut down, call the destruction callback methods.
There are three ways that Spring can recognize your initialization and destruction callback
methods. First, your bean can implement the InitializingBean and DisposableBean life cycle interfaces
and implement the afterPropertiesSet() and destroy() methods for initialization and destruction.
Second, you can set the init-method and destroy-method attributes in the bean declaration and
specify the callback method names. In Spring, you can also annotate the initialization and destruction
callback methods with the life cycle annotations @PostConstruct and @PreDestroy , which are
defined in JSR-250: Common Annotations for the Java Platform. Then you can register a
CommonAnnotationBeanPostProcessor instance in the IoC container to call these callback methods.
How It Works
To understand how the Spring IoC container manages the life cycle of your beans, let's consider an
example involving the checkout function. The following Cashier class can be used to check out the
products in a shopping cart. It records the time and the amount of each checkout in a text file.
public class Cashier {
private String name;
private String path;
private BufferedWriter writer;
public void setName(String name) { = name;
public void setPath(String path) {
this.path = path;
public void openFile() throws IOException {
File logFile = new File(path, name + ".txt");
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile, true)));
Search WWH ::

Custom Search