SpringBoot进阶 CommandLineRunner 初始化配置

在Spring Boot中,CommandLineRunner接口用于在应用程序启动后执行一些特定的命令行操作。通过实现CommandLineRunner接口,您可以在Spring Boot应用程序运行时执行一些自定义的初始化操作,比如读取配置文件、执行特定任务等。

要使用CommandLineRunner接口,您需要创建一个实现该接口的类,并实现其run()方法。在run()方法中,您可以编写要在应用程序启动时执行的命令行操作。以下是一个简单的示例:

 

 

 1 package com.jzt.zhcai.beacon.config;
 2 
 3 import cn.hutool.core.collection.CollectionUtil;import org.apache.commons.lang.exception.ExceptionUtils;import org.springframework.boot.CommandLineRunner;
 4 import org.springframework.stereotype.Component;
 5 import org.springframework.util.CollectionUtils;
 6 
 7 import javax.annotation.Resource;
 8 import java.lang.reflect.Field;
 9 import java.util.*;
10 import java.util.concurrent.TimeUnit;
11 
12 
13 @Component
14 @Slf4j
15 public class MyCommandLineRunner implements CommandLineRunner {
16     
17     @Resource
18     XxxMapper xxxMapper;
19 
20     @Override
21     public void run(String... args) throws Exception {
22         initializeDtConfig();
23     }
24 
25     public void initializeDtConfig() throws Exception {
26         initVisitPurpose();
27         initCustomerConfig();
28     }
29 
30     private void initVisitPurpose() {
31          // do something
32     }
33 
34     private void initCustomerConfig() {
35          // do something
36     } 
37 }

 

 

 

在上面的示例中,我们创建了一个名为MyCommandLineRunner的类,并实现了CommandLineRunner接口的run()方法。在run()方法中,我们编写了一个简单的逻辑,打印出"CommandLineRunner已执行!"的消息。然后,我们使用@Component注解将该类标记为一个Spring组件,以便Spring容器能够在应用程序启动时自动实例化该类并调用其run()方法。

要执行该CommandLineRunner,您需要在Spring Boot应用程序中将该类定义为一个bean,并将其添加到CommandLineRunner列表中。以下是一个示例配置:

 

 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 import org.springframework.boot.CommandLineRunner;
 4 import org.springframework.stereotype.Component;
 5 
 6 @Configuration
 7 public class MyAppConfig {
 8 
 9     @Bean
10     public CommandLineRunner myCommandLineRunner() {
11         return new MyCommandLineRunner();
12     }
13 }

 

 

在上面的示例中,我们创建了一个名为MyAppConfig的配置类,并使用@Bean注解定义了一个名为myCommandLineRunner的方法。该方法返回一个MyCommandLineRunner的实例,并将其注册为一个Spring bean。然后,Spring容器将在应用程序启动时自动将该bean添加到CommandLineRunner列表中,以便在应用程序运行时执行相应的命令行操作。

通过使用CommandLineRunner接口和相应的配置,您可以方便地在Spring Boot应用程序启动时执行自定义的命令行操作。这对于需要在应用程序运行时进行一些特定操作的场景非常有用。

posted @ 2023-09-27 09:14  壹袋米  阅读(122)  评论(0编辑  收藏  举报