search
HomeJavajavaTutorialHow to implement monitoring of springboot application service startup events

    1. Introduction

    Spring Boot provides two interfaces: CommandLineRunner and ApplicationRunner, which are used to do special processing when starting the application. These codes will be used in SpringApplication The run() method is executed before the run is completed. Compared with the Spring's ApplicationListener interface custom listener and Servlet's ServletContextListener listener introduced to you in the previous chapter. The advantage of using both is that you can easily use application startup parameters and perform different initialization operations according to different parameters.

    2. Introduction to common scenarios

    Implement the CommandLineRunner and ApplicationRunner interfaces. Usually used for special code execution before the application starts, such as:

    • Load system commonly used data into memory

    • The last time the application ran Garbage data cleaning

    • Sending notifications after successful system startup, etc.

    I implemented the CommandLineRunner interface and loaded the system when the application started Commonly used configuration data is shown in the figure below. Load the data from the database into the memory. When using the data in the future, you only need to call the getSysConfigList method. There is no need to load the data in the database every time. Save system resources and reduce data loading time.

    How to implement monitoring of springboot application service startup events

    2. Small code experiment is implemented through @Component definition

    CommandLineRunner: The parameter is a string array

    @Slf4j
    @Component
    public class CommandLineStartupRunner implements CommandLineRunner {
        @Override
        public void run(String... args){
            log.info("CommandLineRunner传入参数:{}", Arrays.toString(args));
        }
    }

    ApplicationRunner: The parameter is Put it in ApplicationArguments and get the parameters through getOptionNames(), getOptionValues(), getSourceArgs()

    @Slf4j
    @Component
    public class AppStartupRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args)  {
            log.info("ApplicationRunner参数名称: {}", args.getOptionNames());
            log.info("ApplicationRunner参数值: {}", args.getOptionValues("age"));
            log.info("ApplicationRunner参数: {}", Arrays.toString(args.getSourceArgs()));
        }
    }

    Implemented through @Bean definition

    This method can specify the execution order, pay attention to the first two Beans is CommandLineRunner, and the last Bean is ApplicationRunner.

    @Configuration
    public class BeanRunner {
        @Bean
        @Order(1)
        public CommandLineRunner runner1(){
            return new CommandLineRunner() {
                @Override
                public void run(String... args){
                    System.out.println("BeanCommandLineRunner run1()" + Arrays.toString(args));
                }
            };
        }
    
        @Bean
        @Order(2)
        public CommandLineRunner runner2(){
            return new CommandLineRunner() {
                @Override
                public void run(String... args){
                    System.out.println("BeanCommandLineRunner run2()" + Arrays.toString(args));
                }
            };
        }
    
        @Bean
        @Order(3)
        public ApplicationRunner runner3(){
            return new ApplicationRunner() {
                @Override
                public void run(ApplicationArguments args){
                    System.out.println("BeanApplicationRunner run3()" + Arrays.toString(args.getSourceArgs()));
                }
            };
        }
    }

    You can set the execution order through @Order

    3. Execute the test

    Add the following parameters to the IDEA Springboot startup configuration, save and start the application

    How to implement monitoring of springboot application service startup events

    Test output result:

    c.z.boot.launch.config.AppStartupRunner : ApplicationRunner parameter name: [name, age]
    c.z.boot.launch.config. AppStartupRunner : ApplicationRunner parameter value: [18]
    c.z.boot.launch.config.AppStartupRunner : ApplicationRunner parameter: [--name=zimug, --age=18]

    BeanApplicationRunner run3()[-- name=zimug, --age=18]

    c.z.b.l.config.CommandLineStartupRunner : CommandLineRunner incoming parameters: [--name=zimug, --age=18]
    BeanCommandLineRunner run1()[--name =zimug, --age=18]
    e=18]
    BeanCommandLineRunner run2()[--name=zimug, --age=18]

    The author has tested it many times It was found that in the test results, this priority order has always been like this, but it is currently impossible to determine whether this is the norm

    • ApplicationRunner execution priority is higher than CommandLineRunner

    • The priority of Runner running in the form of Bean is lower than that of Component annotation and implements Runner interface.

    • Order annotation can only guarantee the execution order of the same CommandLineRunner or ApplicationRunner, but cannot Cross-class guaranteed order

    4. Summary

    The core usage of CommandLineRunner and ApplicationRunner is consistent, which is used for special code execution before application startup. The execution order of ApplicationRunner precedes CommandLineRunner; ApplicationRunner encapsulates parameters into objects and provides methods for obtaining parameter names, parameter values, etc., which makes the operation more convenient.

    5. Problem Summary

    This is a real problem that the author encountered in practice, that is, I defined multiple implementations of CommandLineRunner. A strange problem arises: When you define multiple implementations of CommandLineRunner, one or several of them will not execute.

    Analysis: The following code is the code that SpringBootApplication will execute after starting the project. You can see that the CommandLineRunner or ApplicationRunner is started through a traversal in the code. In other words, the next CommandLineRunner will be executed only after the execution of the previous CommandLineRunner is completed, which is executed synchronously.

    private void callRunners(ApplicationContext context, ApplicationArguments args) {
    		List<Object> runners = new ArrayList<>();
    		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
    		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    		AnnotationAwareOrderComparator.sort(runners);
    		for (Object runner : new LinkedHashSet<>(runners)) {
    			if (runner instanceof ApplicationRunner) {
    				callRunner((ApplicationRunner) runner, args);
    			}
    			if (runner instanceof CommandLineRunner) {
    				callRunner((CommandLineRunner) runner, args);
    			}
    		}
    	}

    So, if a synchronous blocking API or a while(true) loop is called in the run method body of an implementation of CommandLineRunner, other implementations after the CommandLineRunner in the traversal will not be executed.

    The above is the detailed content of How to implement monitoring of springboot application service startup events. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.