A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 专注的一批 中级黑马   /  2019-12-19 14:20  /  1469 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

几个重要的事件回调机制:

1、配置在META-INF/spring.factories

ApplicationContextInitializer

SpringApplicationRunlistener

2、需要放在ioc容器中

     3、ApplicationRunner

     4、CommandLineRunner

一、创建SpringApplication对象

快速创建一个工程,在SpringBootApplication类中,main方法作为一个入口类,在在run()方法处打上断点,debug运行;
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    //保存主配置类   
this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    //判断当前是否一个web应用
    this.webApplicationType = WebApplicationType.deduceFromClasspath();
    //从类路径系找到META-INF/spring.factories配置的所有ApplicationContextInitializer,然后保存起来
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    //从类路径系找到META-INF/spring.factories配置的所有ApplicationListener
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    //从多个配置类中找到有main方法的主配置类
    this.mainApplicationClass = deduceMainApplicationClass();
}
二、运行run方法

接着上一步的继续进行:
public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    //获取SpringApplicationRunListeners ,从类路径下METTA-INF/spring.factories
    SpringApplicationRunListeners listeners = getRunListeners(args);
    //回调所有的SpringApplicationRunListeners.starting方法
    listeners.starting();
    try {
        //封装命令行参数
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //准备环境
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        //创建环境完成后回调SpringApplicationRunListeners.environmentPrepared();表示环境准备完成
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        //创建applicationContext,决定创建web的ioc还是普通的ioc
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                        new Class[] { ConfigurableApplicationContext.class }, context);
        //准备上下文环境;将environment保存到ioc中;而且applyInitializers()
        //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的Initialize方法
        //回调所有的SpringApplicationRunListeners.contextPrepared()
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //prepareContext运行完成以后回调所有的SpringApplicationRunListeners的contextLoaded()
        //刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的tomcat);spring注解
        //扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
        refreshContext(context);
        //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
        //ApplicationRunner先回调,CommandLineRunner再回调

        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, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    //整个SpringBoot应用启动完成以后返回启动的ioc容器
    return context;
}三、事件监听机制
依次将上面的几个监听机制进行创建,
HelloApplicationContextInitializer:
function(){ //外汇返佣 http://www.kaifx.cn/
public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer...initialize..." + applicationContext);
    }
}
HelloSpringApplicationRunListener:
public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {
   
    public HelloSpringApplicationRunListener(SpringApplication application, String[] args){

    }

    @Override
    public void starting() {
        System.out.println("SpringApplicationRunListener...starting...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener...environment" +o);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...started");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...running");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener...failed");
    }
   

}
HelloApplicationRunner:
@Component
public class HelloAppicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run..");
    }
}
HelloCommandLineRuinner:
@Component
public class HelloCommandLineRunner implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...run..." + Arrays.asList());
    }
}
前面提到的ApplicationContextInitializer和SpringApplicationRunlistener是需要进行配置的,配置的位置是在META-INF/spring.factories中,因此创建一个META-INF的文件夹,并创建spring.factories文件,
org.springframework.context.ApplicationContextInitializer=\
com.itlaoqi.springbootspringbootapplication.listener.HelloApplicationContextInitializer

org.springframework.context.SpringApplicationRunListener=\
com.itlaoqi.springbootspringbootapplication.listener.HelloSpringApplicationRunListener
配置完成后启动项目即可进行测试。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马