Reputation: 790
There seem to be differing opinions on implementing logic in a Spring Boot web application on startup. But no consensus on "best practice" or a preferred way over others etc.
I have the following code that implements the ApplicationRunner Interface on startup (with some dummy output):
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AppStartupRunner implements ApplicationRunner {
public static int counter;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("Application started with option names : {}",
args.getOptionNames());
log.info("Increment counter");
counter++;
}
}
Is this method considered "proper" (for lack of a better term)? My intention is to run some code to fetch values on startup from a database, store them in using Ehcache, and a few other "initializing" bits.
This seems hackish, so not sure if there is a cleaner or more appropriate way to go about this.
Upvotes: 8
Views: 3886
Reputation: 21134
ApplicationRunner
and CommandLineRunner
are the correct interfaces to implement to execute business logic which require injected dependencies at start-up.
There is not much difference between the two.
CommandLineRunner
will give you access to the raw String
array of parameters passed at startup.
ApplicationRunner
will give you a more structured ApplicationArguments
, but that's all.
You can have multiple start-up runners, and you can even order them.
This seems hackish
No, it's not. ApplicationRunner
and CommandLineRunner
JavaDoc
Interface used to indicate that a bean should run when it is contained within a
SpringApplication
.
Upvotes: 5