springboot启动后执行某些动作

springboot启动后执行某些动作

1.主要是springboot的启动run方法里调用了callRunners,会去调用实现了ApplicationRunner接口的类的方法

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting(bootstrapContext, this.mainApplicationClass);
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			context.setApplicationStartup(this.applicationStartup);
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

2.编写相关调用

此处applicationContext加载完成后进行了输出DeltaConfigApplication start finished !!!!!!!

@Component
public class DeltaConfigApplicationRunner implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(DeltaConfigApplicationRunner.class);

    public void run(ApplicationArguments args) throws Exception {
        logger.info("DeltaConfigApplication start finished !!!!!!!");
    }
}
posted @ 2021-10-20 14:28  SpecialSpeculator  阅读(206)  评论(0编辑  收藏  举报