springboot 項目啟動完成后執行指定代碼的兩種方式


1.情景展示

當我們想在springboot在項目啟動完成后,會有執行某些代碼的需求,比如說:在控制台打印項目的相關信息,如何實現?

實現方式有兩種,具體如下:

2.實現ApplicationRunner接口

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * springboot啟動后自動執行方法
 * @description:
 * @author: Marydon
 * @date: 2020-12-10 11:19
 * @version: 1.0
 * @email: marydon20170307@163.com
 */
@Slf4j
@Component
// 當有多個類實現ApplicationRunner接口時,可以指定其執行順序,值越小優先級越高
@Order(value = 1)
public class BillApplicationRunner implements ApplicationRunner {

    @Resource
    Environment environment;
    /*
     * 啟動結束后會立即執行的方法
     * @attention:
     * @date: 2020年12月10日 0010 11:21
     * @param: args
     * @return: void
     */
    @Override
    public void run(ApplicationArguments args) {
        log.info("通過實現ApplicationRunner接口,在spring boot項目啟動后打印參數");
        try {
            String contextPath = environment.getProperty("server.servlet.context-path");
            if (contextPath == null) {
                contextPath = "/";
            }

            log.info("項目啟動完畢,訪問地址是:{}://{}:{}{}", "http", Inet4Address.getLocalHost().getHostAddress(), environment.getProperty("server.port"), contextPath);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

說明:當有多個類實現ApplicationRunner接口時,可以使用@Order注解指定其執行順序,值越小優先級越高

3.實現CommandLineRunner接口

import code.marydon.encapsulation.http.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * springboot啟動后自動執行方法
 * @description:
 * @author: Marydon
 * @date: 2022/1/27 16:54
 * @version: 1.0
 * @email: marydon20170307@163.com
 */
@Slf4j
@Component
// 當有多個類實現CommandLineRunner接口時,可以指定其執行順序,值越小優先級越高
@Order(value = 2)
public class BillCommandLineRunner implements CommandLineRunner {

    @Resource
    Environment environment;

    /*
     * 啟動結束后會立即執行的方法
     * @attention:
     * @date: 2022/1/27 16:53
     * @param: args
     * @return: void
     */
    @Override
    public void run(String... args) {
        log.info("通過實現CommandLineRunner接口,在spring boot項目啟動后打印參數");
        IpUtils.getAccessPath(environment);
    }
}

說明:當有多個類實現CommandLineRunner接口時,可以使用@Order注解指定其執行順序,值越小優先級越高。

另外,當項目中同時實現了ApplicationRunner和CommondLineRunner接口時,可使用Order注解或實現Ordered接口來指定執行順序,值越小越先執行。

寫在最后

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM