SpringBoot 항목 (칠) ------ 실행 사용자 정의 시작 클래스 방법

springboot 프로젝트는 이것이 우리의 프로젝트의 입구, 시작 클래스를해야하지만 우리가 원하는 때이 프로젝트는 원래 시작 클래스를 사용할 수 없습니다, 다른 일을 시작하고, 우리는 run 메소드의 소스를 보면 :
    public ConfigurableApplicationContext run(String... args) {
		// 创建计时器
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
		
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
		// 设置属性
        this.configureHeadlessProperty();
		
		// spring中监听器的使用,这些对象想创建,就得知道监听器的全路径
		// 会从spring.factory中读取
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        listeners.starting();

        Collection exceptionReporters;
        try {
			// 初始化默认应用参数
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			// 根据监听器和默认的参数 来准备spring所需要的环境
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
			// 打印出banner
            Banner printedBanner = this.printBanner(environment);
			// 创建应用上下文
            context = this.createApplicationContext();
			// 异常报告
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
			// 准备应用上下文	
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			// 刷新上下文
            this.refreshContext(context);
			// 刷新
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            listeners.started(context);
			// 执行callRunners, 支持自定义run方法
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

우리는 마지막 행의 방법 try 블록을 발견callRunners이 방법은 실행 사용자 지정 방법을 지원하고 보러 지적하는 것입니다

    private void callRunners(ApplicationContext context, ApplicationArguments args) {
        List<Object> runners = new ArrayList();
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        Iterator var4 = (new LinkedHashSet(runners)).iterator();

        while(var4.hasNext()) {
            Object runner = var4.next();
            if (runner instanceof ApplicationRunner) {
                this.callRunner((ApplicationRunner)runner, args);
            }

            if (runner instanceof CommandLineRunner) {
                this.callRunner((CommandLineRunner)runner, args);
            }
        }

    }

ApplicationRunner, CommandLineRunner이 두 클래스의 지원 사용자 정의 실행 방법 두 개의 클래스 참조
다음과 같은 절차입니다 :
시작 클래스가 구현 ApplicationRunner 또는 CommandLineRunner 인터페이스 로직 및 다시 실행 방법에 작성된 코드를 수행 할 필요가 같은

package com.jym.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author jym
 */
@SpringBootApplication()
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        new SpringApplication(DemoApplication.class).run();
    }

    public void run(String... args) throws Exception {
        System.out.println("jymQWQ");
    }
}

그래서 프로젝트가 시작 때, 코드는 우리의 구현에 할 필요가

세계에서 사람들이 10 종류가 있습니다, 하나의 바이너리 이해하는 것입니다, 하나는 바이너리 이해하지 않습니다.

당신의 메시지를 작성하지 않는 경우, 감사합니다 경우, 시청 해 주셔서 감사합니다.

게시 71 개 원래 기사 · 원의 찬양 (54) · 전망 420 000 +

추천

출처blog.csdn.net/weixin_43326401/article/details/104079438