SpringBootApplication
使用 spring boot 進行良好的自動包掃描來構建程式碼的最基本方法是使用 @SpringBootApplication 註釋。此註釋本身提供了 3 個有助於自動掃描的其他註釋:@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan(有關 Parameters 部分中每個註釋的更多資訊)。
通常將 @SpringBootApplication 放在主包中,所有其他元件將放在此檔案下的包中:
com
+- example
+- myproject
+- Application.java (annotated with @SpringBootApplication)
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
除非另有說明,否則 spring boot 會在掃描的包裹下自動檢測 @Configuration,@Component,@Repository,@Service,@Controller,@RestController 註釋(@Configuration 和 @RestController 正在被選中,因為它們相應地由 @Component 和 @Controller 註釋)。
基本程式碼示例:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
明確設定包/類
從版本 **1.3 開始,**你還可以通過在 @SpringBootApplication 中設定 scanBasePackages 或 scanBasePackageClasses 而不是指定 @ComponentScan 來告訴 spring boot 掃描特定的包。
@SpringBootApplication(scanBasePackages = "com.example.myproject")- 將com.example.myproject設定為掃描的基礎包。@SpringBootApplication(scanBasePackageClasses = CustomerController.class)-scanBasePackages的型別安全替代品,將CustomerController.java,com.example.myproject.web的包裝作為掃描的基礎包。
不包括自動配置
另一個重要特性是能夠使用 exclude 或 excludeName 排除特定的自動配置類(從版本 1.3 開始存在 excludeName )。
@SpringBootApplication(exclude = DemoConfiguration.class)- 將從自動包掃描中排除DemoConfiguration。@SpringBootApplication(excludeName = "DemoConfiguration")- 將使用類完全分類的名稱來做同樣的事情。