• SpringBoot中实现CommandLineRunner接口在项目启动后立即执行某方法


    场景

    在启动SpringBoot项目的启动类之后需要其立即执行某方法。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    在项目下新建类,使这个类实现CommandLineRunner接口,此接口是springboot自带的,接口定义如下

    package org.springframework.boot;
    
    @FunctionalInterface
    public interface CommandLineRunner {
        void run(String... args) throws Exception;
    }

    实现接口后需要重新run方法,在run方法中执行需要接着执行的逻辑

    package com.ruoyi.web.imserver.config;
    
    import com.ruoyi.web.imserver.ServerLauncherImpl;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    /**
     * <p> 启动MobileIMSDK服务端 </p>
     *
     * @author :
     * @description : run方法在SpringBoot服务启动之后会自动被调用
     * @date :
     */
    
    @Component
    @Order(value = 1)
    public class ChatServerRunner implements CommandLineRunner {
    
        @Override
        public void run(String... strings) throws Exception {
            System.out.println("公众号:霸道的程序猿");
        }
    
    }

    启动SpringBoot的启动类,查看效果

    这里的Order注解的value代表启动的顺序,value值越小,顺讯越在前。 

    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    Calendar日历类
    DateFormat类和SimpleDateFormat类
    Date时间类(java.util.Date)
    时间处理相关类
    不可变和可变字符序列使用陷阱
    String类
    搬圆桌问题
    重温经典之排序 java实现
    i++ 和 ++i
    Intellij Idea 使用技巧 updating
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/14119780.html
Copyright © 2020-2023  润新知