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")- 将使用类完全分类的名称来做同样的事情。