Register Now

Forget Password

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Spring PostConstruct and PreDestroy Annotations

Spring allows us to apply custom actions to bean during its creation and destruction. We can also do it by implementing the InitializingBean and DisposableBean interfaces.

Here we'll look at a second possibility, the @PostConstruct and @PreDestroy annotations.

 

 @PostConstruct

Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties. Keep in mind that these methods will run even if there's nothing to initialize.

The method annotated with @PostConstruct can have any access level, but it can't be static.

One possible use of @PostConstruct  can be populating a database. For an example, during development, we might want to create some default users:

@Component
public class DbInitialization {

    @Autowired
    private UserRepository repository;

    @PostConstruct
    private void postConstruct() {
        User user = new User("test", "password");
        repository.save(user);
    }
}

The above code will first initialize repository and after that it will run the @PostConstruct method.

 

 @PreDestroy

A method annotated with @PreDestroy runs only once that too before Spring removes this bean from the application context.

@Component
public class UserRepository {

    private DbConnection connection;
    @PreDestroy
    public void preDestroy() {
       connection.close();
    }
}

The purpose of this method is to release resources or perform other cleanup tasks, like closing a database connection, before the bean gets destroyed.

 

Note that both  @PostConstruct and @PreDestroy annotations are part of Java EE. Since Java EE was deprecated in Java 9, and removed in Java 11, we have to add an below additional dependency to use these annotations:

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>