@EnableAutoConfiguration和@SpringbootApplication注解


一、@EnableAutoConfiguration

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you 
will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC,
the auto-configuration will assume that you are developing a web application and setup Spring accordingly.

Starters and Auto-Configuration Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied.
You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do
its best to auto-configure your application.

  這個注釋告訴SpringBoot“猜”你將如何想配置Spring,基於你已經添加jar依賴項。如果spring-boot-starter-web已經添加Tomcat和Spring MVC,這個注釋自動將假設您正在開發一個web應用程序並添加相應的spring設置。

  自動配置被設計用來和“Starters”一起更好的工作,但這兩個概念並不直接相關。您可以自由挑選starter依賴項以外的jar包,springboot仍將盡力自動配置您的應用程序。

  spring通常建議我們將main方法所在的類放到一個root包下,@EnableAutoConfiguration(開啟自動配置)注解通常都放到main所在類的上面,下面是一個典型的結構布局:

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

  這樣@EnableAutoConfiguration可以從逐層的往下搜索各個加注解的類,例如,你正在編寫一個JPA程序(如果你的pom里進行了配置的話),spring會自動去搜索加了@Entity注解的類,並進行調用

二、@SpringbootApplication

   使用@SpringbootApplication注解  可以解決根類或者配置類(我自己的說法,就是main所在類)頭上注解過多的問題,一個@SpringbootApplication相當於@Configuration,@EnableAutoConfiguration和 @ComponentScan 並具有他們的默認屬性值

package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication 
public class Application {    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM