Back to Javatutorial

SpringBoot启动流程(五):完成启动

docs/Spring全家桶/SpringBoot源码解析/SpringBoot启动流程(五):完成启动.md

1.0.02.6 KB
Original Source

һƪܽ springboot £

ģǼIJ衣

3.11 ˢºĴ

ˢºĴΪ SpringApplication#afterRefresh£

protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}

Կһշspringboot ṩչ

3.12 started ¼

òķΪ listeners.started(context)߼ǰѾͲٷˡ

3.13 ص

ķ SpringApplication#callRunners£

private void callRunners(ApplicationContext context, ApplicationArguments args) {
    List<Object> runners = new ArrayList<>();
    // ȡе ApplicationRunner  CommandLineRunner
    runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
    runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    // 
    AnnotationAwareOrderComparator.sort(runners);
    // 
    for (Object runner : new LinkedHashSet<>(runners)) {
        //  ApplicationRunner#run 
        if (runner instanceof ApplicationRunner) {
            callRunner((ApplicationRunner) runner, args);
        }
        //  CommandLineRunner#run 
        if (runner instanceof CommandLineRunner) {
            callRunner((CommandLineRunner) runner, args);
        }
    }
}

/**
 *  ApplicationRunner#run 
 */
private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
    try {
        (runner).run(args);
    }
    catch (Exception ex) {
        throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
    }
}

/**
 *  CommandLineRunner#run 
 */
private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
    try {
        (runner).run(args.getSourceArgs());
    }
    catch (Exception ex) {
        throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
    }
}

ʾspringboot ΪṩӿڣApplicationRunner CommandLineRunnerǿʵһЩӦʾ£

/**
 * ApplicationRunner ʾ
 */
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("MyApplicationRunner: hello world");
    }
}

/**
 * CommandLineRunner ʾ
 */
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner: hello world!");
    }
}

3.14 м listeners.running(...)

ͬǰ listeners.starting() ·һͲˡ

ˣĵķ͵ˣ springboot ̵ķҲˡ


ԭӣhttps://my.oschina.net/funcy/blog/4906553 ߸ˮƽд֮ӭָԭףҵתϵ߻Ȩҵתע