Explain Codes LogoExplain Codes Logo

Execute method on startup in Spring

java
spring-boot
dependency-injection
bean-lifecycle
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

Utilize @PostConstruct for executing a startup method after dependency injection but without command-line arguments.

@PostConstruct public void onStartup() { // Pro tip: write elegant logic here, not spaghetti code }

For accessing command-line arguments at startup, leverage the CommandLineRunner interface.

@Override public void run(String...args) { // Toss in arguments, like you'd toss pizza dough }

Both of these methods integrate with Spring's lifecycle—choose based on your needs regarding command-line arguments.

Decoding Spring startup rituals

When Spring boots up, it can dancer-style "twist and turn" to run your specific methods. Here are some ways to make Spring put its favorite track on and "hit the dance floor".

The @PostConstruct jaunt

@PostConstruct is the simplest dance step. If you want something executed after dependency injection is done, it's your go-to move. The method runs once, right after the bean's born, and that's it.

The InitializingBean motion

The InitializingBean interface is a bit more sophisticated. Implement it if you want a method to be executed after Spring has set the bean's properties. A great move if you prefer control over the initialization beat.

The init() groove

You can also groove with a unique init() method, labeling it with @Bean(initMethod="init") to make it your initialization routine. Introducing: your personal signature dance move!

The Lifecycle whirl

The Lifecycle interface obliges you to specify start() and stop() methods. Implement it to twist your bean according to the dance of the context's lifecycle itself.

The Application event shimmy

Boggie down post-context initialization using ApplicationListener<ContextRefreshedEvent> or @EventListener.

Remember, these moves are triggered each time the context refreshes, so if you faced this DJ before, they tend to play the same track repeatedly.

The ApplicationReadyEvent samba

To shake things up post-startup, groove with ApplicationReadyEvent and @EventListener. This way, your method will boogie down when the whole application is fully initialized and ready to serve requests.

Choosing the right dance moves

The choice of dance moves depends on the preference of your application. Let's see what might suit your app the best.

Starting with Two-Step

@PostConstruct is like the Two-Step. Simple, effective, and perfect for lightweight initialization tasks;

Tango with the bean lifecycle

Implementing the InitializingBean interface or creating custom init() methods is like performing an intricate tango. You control each step and twirl, making it suitable for more complex performances.

Dance off with startup events

Understanding Spring context events (i.e., ApplicationListener<ContextRefreshedEvent> and @EventListener) is like getting your moves "on beat".

Bringing your Jive

Just going to a direct bean method invocation is the equivalent of free styling or Jive. It's easy-going, clean, and sometimes, the most enjoyable.

Ensuring a one-time show

However, make sure your show is designed for a one-time performance - you don't want your actors to accidentally encore due to any intermissions or other events.

Travel light for your dance

Don't pack too heavily for the dance. Avoid introducing too many dance props or going overboard with complex lighting setups specifically for startup dances.

Dance with the Spring

In the auditorium of your application, your "actors" (beans) need a well-choreographed setup (context initialization).

Mastering the moves

Lifecycle hooks teach our actors (beans) their "entrances and exits" (initialization).

The grand performance

A flawless performance (application) requires a balance between automation (annotations) and manual direction (explicit configuration).

Behind the scenes

The life of every actor (bean), from its audition (construction) to its standing ovation (fully initialized bean), is a critical chapter of the production that is your Spring application.

The unexpected script changes (Exceptions)

For those unexpected plot twists (exceptions), our actors are well-rehearsed during rehearsals (error handling and logging).