Spring Boot起動方法run()ソース解析


入り口
通常は簡単なSprigBootの基礎プロジェクトです。私たちは下記のコードがあります。

@SpringBootApplication
@RestController
@RequestMapping("/")
public class Application {

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

}
注目すべきは、SpringApple.runと注釈@SprigBootApplicationです。
runメソッド

public ConfigurableApplicationContext run(String... args) {
	 //   
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		//      
		SpringApplicationRunListeners listeners = getRunListeners(args);
		//      
		listeners.starting();
		try {
		 // application       
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			//      bean  
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			//        
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
		 //      ,  bean
			prepareContext(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, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
		 //        
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
getRunListeners
モニターを取得

private SpringApplicationRunListeners getRunListeners(String[] args) {
		Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
		//    Spring Factory     
		return new SpringApplicationRunListeners(logger,
				getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
	}


	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		//    spring.factories
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		//   SpringFactory  
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		/**
		 *    {@link Ordered}
		 */
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

createSpringFactoriesInstances

 @SuppressWarnings("unchecked")
 private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
 		ClassLoader classLoader, Object[] args, Set<String> names) {
 //    
 	List<T> instances = new ArrayList<>(names.size());
 	for (String name : names) {
 		try {
 		 //         class  
 			Class<?> instanceClass = ClassUtils.forName(name, classLoader);
 			Assert.isAssignable(type, instanceClass);
 			//      
 			Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
 			//       
 			T instance = (T) BeanUtils.instantiateClass(constructor, args);
 			//       
 			instances.add(instance);
 		}
 		catch (Throwable ex) {
 			throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
 		}
 	}
 	return instances;
 }
print Banner

private Banner printBanner(ConfigurableEnvironment environment) {
		if (this.bannerMode == Banner.Mode.OFF) {
			return null;
		}
		ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
				: new DefaultResourceLoader(getClassLoader());
		//      
		SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
		if (this.bannerMode == Mode.LOG) {
		 //   
			return bannerPrinter.print(environment, this.mainApplicationClass, logger);
		}
 //   
		return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
	}
	Banner print(Environment environment, Class<?> sourceClass, PrintStream out) {
		Banner banner = getBanner(environment);
		banner.printBanner(environment, sourceClass, out);
		return new PrintedBanner(banner, sourceClass);
	}
最終出力内容類:org.springframe ebook.boot.SprigBoot Banner

class SpringBootBanner implements Banner {

	private static final String[] BANNER = { "", " . ____  _  __ _ _",
			" /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\", "( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\",
			" \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )", " ' |____| .__|_| |_|_| |_\\__, | / / / /",
			" =========|_|==============|___/=/_/_/_/" };

	private static final String SPRING_BOOT = " :: Spring Boot :: ";

	private static final int STRAP_LINE_SIZE = 42;

	@Override
	public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) {
		for (String line : BANNER) {
			printStream.println(line);
		}
		String version = SpringBootVersion.getVersion();
		version = (version != null) ? " (v" + version + ")" : "";
		StringBuilder padding = new StringBuilder();
		while (padding.length() < STRAP_LINE_SIZE - (version.length() + SPRING_BOOT.length())) {
			padding.append(" ");
		}

		printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT, AnsiColor.DEFAULT, padding.toString(),
				AnsiStyle.FAINT, version));
		printStream.println();
	}

}
今回のspringboot起動方法の解読を通じて、springbootの下層部について大体理解してもらいたいです。主要な方法だけを分析して、皆さんに助けてほしいです。
ここでSpringBootの起動方法run()のソースコードについての記事を紹介します。Spring Bootの起動に関する詳細な内容は以前の記事を検索してください。または下記の関連記事を引き続きご覧ください。これからもよろしくお願いします。