Spring Boot 注解 @SpringBootApplication的使用详解
目录
- @SpringBootApplication注解
- 一、编程简介
- 二、使用
- 1.指定要扫描的包
@SpringBootApplication注解
一、简介
@SpringBootApplication
是 Spring Boot 提供的一个注解,通常用于启动类(主类)上,它是三个注解的组合:
@Configuration
表示该类是一个配置类,等价于 XML 配置文件。
2.@EnableAutoConfiguration
3.@ComponentScan
二、使用
1.javascript指定要扫描的包
默认情况下,@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 包下javascript,比如它在 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 MyCfGlScHgApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
.yaml文件如下:
demo: info: base-package: com.demo
注:
自定义starter使用@AutoConfiguration注解,无需将其路径放入扫描路径中。
到此这篇关于Spring Boot 注解 @SpringBootApplication的使用详解的文章就介绍到这了,更多http://www.devze.com相关Spring Boot 注解 @SpringBootApplication内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论