Spring – Bean lifecycle using annotations

Facebooktwitterredditpinterestlinkedinmailby feather

Spring – Bean lifecycle using annotations

We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we are going to use annotations for the init-method and destroy-method.

The lifecycle of beans is created and managed by the Spring container and Spring bean, respectively. The bean lifecycle consists of two methods: post-initialization and pre-destruction

Following are the annotations applied to declare the methods:

@PostConstruct – When we use @PostConstruct annotation to annotate a method in the bean, it executes after the initialization of the Spring bean. In other words, it is used to define a method as an initialization method that executes after the dependency injection.

@PreDestroy – When we use @PreDestroy annotation to annotate a method in the bean, it will execute when the bean instances are getting removed from the Spring container. In other words, it is used to define a method as a destruction method that performs a task before the bean destruction.

For scope =” prototype,” Spring container does not call the @PreDestroy method. The Spring container does not completely manage the lifecycle of a prototype bean. The Spring container does not completely manage the lifecycle of a prototype bean.

To use the above annotations, we have to add the following dependency into pom.xml:

Example of bean lifecycle using annotations

Here, we are going to create an example using the @PostConstruct and @PreDestroy annotations for initialization and destruction callback methods, respectively. The Airtel_Sim class implements the Sim interface and its unimplemented method.

Sim.java

Airtel_Sim.java

In the above code, we have defined the @PostConstruct and @PreDestroy annotations just above the doStartUp() and doShutDown() method, respectively.

ApplicationContext.xml

App.java

Output

Example of bean lifecycle using annotations

Facebooktwitterredditpinterestlinkedinmailby feather