When building applications with Micronaut, we often need to execute some logic when the application starts. This could include tasks like initializing resources, seeding a database, or logging system information.
In this article, we will explore how to run startup code in Micronaut using ApplicationEventListener and @EventListener.
Table of contents
- 1. Implements ApplicationEventListener to Run Startup Code
- 2. Using @EventListener to Run Startup Code
- 3. Download Source Code
- 4. References
Technologies used:
- Java 21
- Micronaut 4.7.6
- Maven 3.9
1. Implements ApplicationEventListener to Run Startup Code
One of the simplest ways to execute startup logic in Micronaut is by implementing ApplicationEventListener<ServerStartupEvent>. This ensures the logic runs when the application starts.
package com.mkyong;
import io.micronaut.context.event.ApplicationEventListener;
import io.micronaut.runtime.server.event.ServerStartupEvent;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class StartupListener implements ApplicationEventListener<ServerStartupEvent> {
private static final Logger LOG = LoggerFactory.getLogger(StartupListener.class);
@Override
public void onApplicationEvent(ServerStartupEvent event) {
LOG.info("Micronaut application has started!");
runStartupTasks();
}
private void runStartupTasks() {
LOG.info("Performing startup tasks such as initializing resources.");
}
}
Run the application:
package com.mkyong;
import io.micronaut.runtime.Micronaut;
public class Application {
public static void main(String[] args) {
Micronaut.run(Application.class, args);
}
}
Output
__ __ _ _
| \/ (_) ___ _ __ ___ _ __ __ _ _ _| |_
| |\/| | |/ __| '__/ _ \| '_ \ / _` | | | | __|
| | | | | (__| | | (_) | | | | (_| | |_| | |_
|_| |_|_|\___|_| \___/|_| |_|\__,_|\__,_|\__|
16:21:52.237 [main] INFO com.mkyong.StartupListener - Micronaut application has started!
16:21:52.237 [main] INFO com.mkyong.StartupListener - Performing startup tasks such as initializing resources.
16:21:52.240 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 417ms. Server Running: http://localhost:8080
2. Using @EventListener to Run Startup Code
Another approach is to use @EventListener to listen for StartupEvent. This is useful when specific beans need initialization on startup.
package com.mkyong;
import io.micronaut.context.event.StartupEvent;
import io.micronaut.runtime.event.annotation.EventListener;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class DatabaseService {
private static final Logger LOG = LoggerFactory.getLogger(DatabaseService.class);
@EventListener
void init(StartupEvent event) {
LOG.info("Database init has started!");
// simulate database connection
}
}