面试题- Springboot 启动完成之后去执行某些操作

Springboot 启动完成之后去执行某些操作

1 启动类调用实现

public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
		// 启动完成调用自定义方法
		ConditionTest conditionTest = SpringBeanUtil.getBean(ConditionTest.class);
		conditionTest.test();
	}

2 继承 CommandLineRunner

import com.cdchen.study.service.ConditionTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 *
 * @description: ConditionTest
 *
 * @author: cdchen
 *
 * @create: 2019-05-24 11:19
 **/
@Component
public class ConditionTestRunner implements CommandLineRunner {
    @Autowired
    private ConditionTest conditionTest;
    @Override
    public void run(String... strings) throws Exception {
    // 启动完成调用自定义方法
        conditionTest.test();
    }
}

3 继承 ApplicationRunner

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
 *
 * @description: ApplicationRunner
 *
 * @author: cdchen
 *
 * @create: 2019-05-24 16:20
 **/
 @Component
public class ApplicationTestRunner implements ApplicationRunner, Ordered {
    @Override
    public int getOrder(){
        return 1;//通过设置这里的数字来知道指定顺序
    }

    @Override
    public void run(ApplicationArguments var1) throws Exception{
        System.out.println("MyApplicationRunner1!");
    }

}

可通过继承Order接口进行 runner排序,也可以使用@Order注解

你可能感兴趣的:(springCloud,面试题)