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
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment