The blog is originally published on my blog jsblogs.github.io
\n\n\n\n\n \n\n
\n \n \n Introduction \n
\n\nHave you ever encountered a situation where you\'ve to perform some tasks immediately after the Spring/SpringBoot application starts. i.e.
\nInitialize some data into database, initialize application level constants, make an API call, etc.
There are several ways to achieve it. Here I\'m gonna discuss about:
\n\n- \n
- Application events\n
- ApplicationRunner\n
\n \n \n Technologies used \n
\n\n- \n
- Java 11\n
- Spring Boot 2.2.4\n
- Gradle 6.0.1\n
\n \n \n Application events \n
\n\nThe Spring framework triggers various events. For our use case we\'ll be more interested in ContextStartedEvent
and ContextRefreshedEvent
.
\nContextStartedEvent event triggered at the time of context gets started.
\nContextRefreshedEvent event triggered at the time of context gets started or refreshed.
\n
@Component\npublic class EventHandler {\n @EventListener(ContextStartedEvent.class)\n public void handleContextStartEvent(ContextStartedEvent e) {\n // Write your code here\n }\n\n @EventListener(ContextRefreshedEvent.class)\n public void handleContextRefreshEvent(ContextRefreshedEvent e) {\n // Write your code here\n }\n // Or you can handle both the events in 1 method \n\n @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})\n public void handleBoth(ApplicationContextEvent e) {\n if (e instanceof ContextStartedEvent) {\n\n } else {\n\n }\n }\n}\n
\n \n \n ApplicationRunner \n
\n\nSpringBoot provides an interface called ApplicationRunner
, any bean implementing this interface should run when that contained in the SpringApplication
.
\n
@Component\npublic class DBInitializer implements ApplicationRunner {\n\n private final UserRepository userRepository;\n\n private DBInitializer(UserRepository userRepository) {\n this.userRepository = userRepository;\n }\n\n @Override\n public void run(ApplicationArguments args) throws Exception {\n // Initialize user here\n }\n}\n
or the above can be used
\n
@Configuration\npublic class Config {\n\n@Bean\n public ApplicationRunner initializeUser(UserRepository userRepository) {\n return args -> {\n // Initialize user here\n };\n }\n}\n
ApplicationRunner provides ApplicationArguments
in the run method which is used to get command line arguments by invoking getSourceArgs()
.
\nYou can also get the parsed arguments using this class. i.e.
Let\'s say you\'ve passed command line arguments like
\n--source /usr/local --print-only --target /tmp/local
So the method call to
\n\n- \n
- \n
getOptionNames()
inApplicationArguments
will return set of arguments - [\'source\', \'print-only\', \'target\']\n - \n
containsOption(String name)
checks if argument contains \n - \n
getOptionValues(name)
returns list of option values.getOptionValues(\'source\')
will return list - [\'/usr/local\']\n