java / beginner
Snippet
Executing Logic on Startup
The CommandLineRunner interface is used to run specific code immediately after the Spring application context has been fully initialized. This is ideal for one-time setup tasks or seed data generation.
snippet.java
1
2
3
4
5
6
7
@Componentpublic class StartupRunner implements CommandLineRunner {@Overridepublic void run(String... args) {System.out.println("The Spring application has started!");}}
spring
Breakdown
1
@Component
Registers this class as a Spring-managed bean so it can be automatically detected.
2
implements CommandLineRunner
The interface that grants access to the startup execution hook.
3
public void run(String... args)
The method where your startup logic is placed; 'args' contains any command-line arguments.