It’s often necessary to run some startup code when an application starts. For example, in a test environment, you can add some test records. Or, you can add an admin user on new installations.

There are many to do this in a Spring application. Let’s discuss a couple.

Using @PostConstruct

Spring provides various mechanisms to control the lifecycle of components. For example, you can annotate component methods with @PostConstruct or @PreDestroy, and those will be called by Spring after the component is constructed (i.e. all the injections in the component have been done) or before it is destroyed.

So, we can use @PostConstruct to run some code at startup, as below:

@Service
public class UserServiceImpl implements UserService {
    private static final Log log = LogFactory.getLog(UserServiceImpl.class);
    @PostConstruct
    public void postConstruct() {
        log.info("UserServiceImpl constructed");
    }
    ...
}

But, a better way to run some code at startup would be to write a listener, listening to the application-ready event.

Application events and listeners

For executing code at various application events, Spring allows us to write listener methods. For example, if we write a listener for the ApplicationReadyEvent, that will get executed after the application is ready.

Listener methods can be coded inside any component, as below:

@Service
public class UserServiceImpl implements UserService {
     private static final Log log = LogFactory.getLog(UserServiceImpl.class);
    @EventListener
    public void afterApplicationReady(ApplicationReadyEvent event) {
        log.info("Application now ready!");
    }
    ...
}

For the event listening to work, I’ve noticed that Spring requires its signature to be coded in one of the interfaces that the component implements. So, we can declare its signature in the UserService interface that the UserServiceImpl above implements:

public interface UserService {
    ...
    void afterApplicationReady(ApplicationReadyEvent event);
}

Found this useful? You may like to go through our Spring Framework Tutorial - Course III, which covers in great details the essential patterns like this one that you’ll find very useful when developing a real-world Spring application.