Spring Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:


1. Introduction

Spring allows us to attach custom actions to bean creation and destruction. We can, for example, do it by implementing the InitializingBean and DisposableBean interfaces.

In this short tutorial, we'll look at a second possibility: the @PostConstruct and @PreDestroy annotations.

2. @PostConstruct

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

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

One example usage of @PostConstruct is populating a database. During development, for instance, we might want to create some default users:

public class DbInit {

    private UserRepository userRepository;

    private void postConstruct() {
        User admin = new User("admin", "admin password");
        User normalUser = new User("user", "user password");
        userRepository.save(admin, normalUser);

The above example will first initialize UserRepository and then run @PostConstruct method.

3. @PreDestroy

A method annotated with @PreDestroy runs only once, just before Spring removes our bean from the application context.

Same as with @PostConstruct, the methods annotated with @PreDestroy can have any access level but can't be static.

public class UserRepository {

    private DbConnection dbConnection;
    public void preDestroy() {

The purpose of this method should be to release resources or perform any other cleanup tasks before the bean gets destroyed, for example closing a database connection.

4. Java 9+

Note that both @PostConstruct and @PreDestroy annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations:


5. Conclusion

In this short tutorial, we've learned how to use @PostConstruct and @PreDestroy annotations.

As always all source code is available on GitHub.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Inline Feedbacks
View all comments
Comments are closed on this article!