SpringBoot中CommandLineRunner和AplicationRunner

在SpringBoot開發項目的時候,有時需要在Spring容器啓動的時候執行一系列操作。在SpringBoot中提供了兩個接口來實現這樣的需求。
這兩個接口爲:CommandLineRunner和ApplicationRunner

這兩個都有run方法,但是CommandLineRunner的參數爲String數組,ApplicationRunner爲ApplicationArguments。

CommandLineRunnerde實現

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartUpCommandLineRunner implements CommandLineRunner {

    private Logger logger =LoggerFactory.getLogger(MyStartUpCommandLineRunner.class);
    @Override
    public void run(String... strings) throws Exception {

        logger.info("------>MyStartUpCommandLineRunner<-----");
    }
}

ApplicationRunner的實現

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MYStartUpApplicationRunner implements ApplicationRunner {


    private Logger logger = LoggerFactory.getLogger(MYStartUpApplicationRunner.class);
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        logger.info("------>MYStartUpApplicationRunner<------");
    }
}

兩個接口可以同時在一個項目中使用,存在多個的時候可以用@Order()註解來定義優先級。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章