Spring PostConstruct and PreDestroy Annotations

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:

@Component
public class DbInit {

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    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.

@Component
public class UserRepository {

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

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:

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

5. Conclusion

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

As always all source code is available on
GitHub.

Leave a Reply

Your email address will not be published.