SpringBoot註解@SpringBootApplication @EnableAutoConfiguration @ComponentScan @Configuration

1、@SpringBootApplication

   在main函數內
@SpringBootApplication = (默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan.也就是SpringBoot將三個註解統一爲@SpringBootApplication。

@SpringBootApplication // 等同於 @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
	public static void main(String[] args) {
		///
	}
}

1.1 @EnableAutoConfiguration

 該註解用於定義配置類,以替換xml的配置文件。被註解的類內部包含有一個或多個被@Bean註解的方法,相當於xml文件中的標籤。

@EnableAutoConfiguration
public class SpringBootDemo1 {
	@RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }
 
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootDemo1.class, args);//運行spring應用程序
    }
}

   上面的代碼如果不加@EnableAutoConfiguration註解,就會報錯:
Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean。或者加@SpringBootApplication註解也可以解決。
這裏寫圖片描述

1.2 @ComponentScan

   定義掃描路徑,該包路徑下的@Component, @Service, @Repository, @Controller 等類都會被自動裝載到容器內。

1.3 @Configuration

   允許在上下文中註冊其他的bean或導入額外的配置類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章