How 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.
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
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!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
