【Spring Boot 注解】@SpringBootApplication
文章目录
- @SpringBootApplication注解
- 一、简介
- 二、使用
- 1.指定要扫描的包
@SpringBootApplication注解
一、简介
@SpringBootApplication
是 Spring Boot 提供的一个注解,通常用于启动类(主类)上,它是三个注解的组合:
1.@Configuration
表示该类是一个配置类,等价于 XML 配置文件。
2.@EnableAutoConfiguration
告诉 Spring Boot 启动自动配置功能,根据类路径下的依赖、配置等自动配置 Spring 应用。
3.@ComponentScan
启动组件扫描,默认扫描当前类所在包及其子包,将标注了如 @Component、@Service、@Repository、@Controller 等注解的类注入 Spring 容器。
二、使用
1.指定要扫描的包
默认情况下,@SpringBootApplication
会从它所在的包开始向下递归扫描所有子包中的组件(如 @Component
、@Service
、@Repository
、@Controller
、@Configuration
等)。
如果你的项目中有一些组件不在 @SpringBootApplication
所在包的子包里,就需要手动设置 scanBasePackages
来指定需要扫描的包路径。
示例如下:
@SpringBootApplication(scanBasePackages = {"com.demo.module.system", "com.demo.module.infra"})
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
使用场景
- 你的启动类 MyApplication 不在 com.demo 包下,比如它在 com.demo.core,而系统模块和基础设施模块分别在 com.demo.module.system 和 com.demo.module.infra 中。这种情况下,默认的扫描不会覆盖 module.system 和 module.infra,你就需要手动指定
scanBasePackages
。 - 你只希望扫描部分包,而不是整个项目的包。这样能减少启动时的扫描开销,提高性能。
补充
使用 ${} 来注入配置属性值,如下:
@SpringBootApplication(scanBasePackages = {"${demo.info.base-package}.server", "${demo.info.base-package}.module"})
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
.yaml文件如下:
demo:info:base-package: com.demo
注:
自定义starter使用@AutoConfiguration注解,无需将其路径放入扫描路径中。