In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use CommandLineRunner and Application". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use CommandLineRunner and Application".
Detailed explanation of application startup data initialization interfaces CommandLineRunner and Application
Creating a component class in the SpringBoot project to implement the CommandLineRunner or ApplicationRunner interface can realize some initialization operations in time after the application is started, such as cache preheating, index reconstruction and so on.
Both interfaces have the same function, and both have a run method that needs to be overridden, but with different parameters to implement the method.
CommandLineRunner receives the original command line startup parameters, and ApplicationRunner objectifies the startup parameters.
1 timing of operation
Both interfaces run after the SpringBoot application initializes the context, so you can use all the information in the context, such as some Bean, and so on. In the run method of the source code of the framework SpringApplication class, you can view the call timing callRunners of Runner, as follows:
/ * * Run the Spring application, creating and refreshing a new * {@ link ApplicationContext}. * @ param args the application arguments (usually passed from a Java main method) * @ return a running {@ link ApplicationContext} * / public ConfigurableApplicationContext run (String... Args) {StopWatch stopWatch = new StopWatch (); stopWatch.start (); ConfigurableApplicationContext context = null; Collection exceptionReporters = new ArrayList (); configureHeadlessProperty (); SpringApplicationRunListeners listeners = getRunListeners (args); listeners.starting (); try {ApplicationArguments applicationArguments = new DefaultApplicationArguments (args); ConfigurableEnvironment environment = prepareEnvironment (listeners, applicationArguments); configureIgnoreBeanInfo (environment) Banner printedBanner = printBanner (environment); context = createApplicationContext (); exceptionReporters = getSpringFactoriesInstances (SpringBootExceptionReporter.class, new Class [] {ConfigurableApplicationContext.class}, context); prepareContext (context, environment, listeners, applicationArguments, printedBanner); refreshContext (context); afterRefresh (context, applicationArguments) StopWatch.stop (); if (this.logStartupInfo) {new StartupInfoLogger (this.mainApplicationClass) .logStarted (getApplicationLog (), stopWatch);} listeners.started (context); / / call Runner to perform initialization operation callRunners (context, applicationArguments) } catch (Throwable ex) {handleRunFailure (context, ex, exceptionReporters, listeners); throw new IllegalStateException (ex);} try {listeners.running (context);} catch (Throwable ex) {handleRunFailure (context, ex, exceptionReporters, null); throw new IllegalStateException (ex) } return context;} 2 implementation interface
2.1 CommandLineRunner
The simple implementation is as follows: print the startup parameter information:
@ Order (1) @ Componentpublic class CommandLineRunnerInit implements CommandLineRunner {private Logger logger = LoggerFactory.getLogger (this.getClass ()); private final String LOG_PREFIX = "> CommandLineRunner >"; @ Override public void run (String...) Args) throws Exception {try {this.logger.error ("{} args: {}", LOG_PREFIX, StringUtils.join (args, ",");} catch (Exception e) {logger.error ("CommandLineRunnerInit run failed", e);}
2.2 ApplicationRunner
The simple implementation is as follows: print the startup parameter information and call the method of Bean (query the number of users):
Order (2) @ Componentpublic class ApplicationRunnerInit implements ApplicationRunner {private Logger logger = LoggerFactory.getLogger (this.getClass ()); private final String LOG_PREFIX = "> ApplicationRunner >"; private final UserRepository userRepository; public ApplicationRunnerInit (UserRepository userRepository) {this.userRepository = userRepository;} @ Override public void run (ApplicationArguments args) throws Exception {try {this.logger.error ("{} args: {}", LOG_PREFIX, JSONObject.toJSONString (args)) For (String optionName: args.getOptionNames ()) {this.logger.error ("{} argName: {} argValue: {}", LOG_PREFIX, optionName, args.getOptionValues (optionName));} this.logger.error ("{} user count: {}", LOG_PREFIX, this.userRepository.count ()) } catch (Exception e) {logger.error ("CommandLineRunnerInit run failed", e);} 3 execution order
If multiple Runner are implemented, by default, the implementation of ApplicationRunner and then the implementation of CommandLineRunner will be executed in the order in which they are added. If the initialization logic among multiple Runner is in order, you can add @ Order annotation to the implementation class to set the execution order, which can be found in the callRunners method of the source code SpringApplication class, as shown below:
Private void callRunners (ApplicationContext context, ApplicationArguments args) {List runners = new ArrayList (); / / the first added ApplicationRunner implementation runners.addAll (context.getBeansOfType (ApplicationRunner.class). Values ()); / / the added CommandLineRunner implementation runners.addAll (context.getBeansOfType (CommandLineRunner.class). Values ()); / / if the order is set, reorder AnnotationAwareOrderComparator.sort (runners) in the set order For (Object runner: new LinkedHashSet (runners)) {if (runner instanceof ApplicationRunner) {callRunner ((ApplicationRunner) runner, args);} if (runner instanceof CommandLineRunner) {callRunner ((CommandLineRunner) runner, args);} 4 set startup parameters
To facilitate the comparison, set the startup parameters in Idea as follows (command line startup parameters are automatically read in the production environment):
5 running effect
Of the two Runner above, CommandLineRunnerInit is set to be the first and ApplicationRunnerInit to be the second. Start the application, and the running effect is as follows:
Differences in usage between ApplicationRunner and CommandLineRunner
Business scenario:
When the application service starts, load some data and perform some initialization actions of the application. Such as: delete temporary files, clear cache information, read configuration file information, database connection and so on.
1. SpringBoot provides CommandLineRunner and ApplicationRunner interfaces. When the interface has multiple implementation classes, the @ order annotation is provided to implement the custom execution order, or the Ordered interface to customize the order.
Note: the smaller the number, the higher the priority, that is, the @ Order (1) annotated class will execute before the @ Order (2) annotated class.
The difference between the two is:
The parameter of the run method in ApplicationRunner is ApplicationArguments, while the parameter of the run method in the CommandLineRunner interface is the String array. To get command line arguments in more detail, use the ApplicationRunner interface
ApplicationRunner@Component@Order (value = 10) public class AgentApplicationRun2 implements ApplicationRunner {@ Override public void run (ApplicationArguments applicationArguments) throws Exception {}} CommandLineRunner@Component@Order (value = 11) public class AgentApplicationRun implements CommandLineRunner {@ Override public void run (String...) Strings) throws Exception {}} Thank you for your reading. The above is the content of "how to use CommandLineRunner and Application". After the study of this article, I believe you have a deeper understanding of how to use CommandLineRunner and Application, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.