1. 程式人生 > >Spring Boot 2.0深度實踐之核心技術篇(二)

Spring Boot 2.0深度實踐之核心技術篇(二)

#spring自動裝配

  1. 啟用自動裝配:@EnableAutoConfiguration
  2. 實現自動裝配:@XXXConfiguration
  3. 配置自動裝配實現:META-INF/spring.factories

#理解 SpringApplication

  • SpringApplication的執行
    • SpringApplication.run
    • SpringApplicationBuilder.run
  • 配置spring bean源
public class SpirngBootApplication {

    public static void main(String[] args) {

        Set<String> stringSet = new HashSet<>();
        stringSet.add(SpringConfig.class.getName());
        SpringApplication springApplication = new SpringApplication();
        springApplication.setSources(stringSet);

        ConfigurableApplicationContext context = springApplication.run(args);
        System.out.println(context.getBean(SpringConfig.class));
    }
 
    @SpringBootApplication
    public static class SpringConfig {

    }
}
  • 推斷web應用型別
public enum WebApplicationType {

	/**
	 * The application should not run as a web application and should not start an
	 * embedded web server.
	 */
	NONE,

	/**
	 * The application should run as a servlet-based web application and should start an
	 * embedded servlet web server.
	 */
	SERVLET,

	/**
	 * The application should run as a reactive web application and should start an
	 * embedded reactive web server.
	 */
	REACTIVE

}

通過執行緒堆疊來推斷引導類

	private Class<?> deduceMainApplicationClass() {
		try {
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		}

在這裡插入圖片描述在這裡插入圖片描述