- Spring Boot+Vue全栈开发实战
- 王松
- 396字
- 2025-02-20 10:40:50
2.2 @Spring BootApplication
在前文的介绍中,读者已经了解到@Spring BootApplication注解是加在项目的启动类上的。@Spring BootApplication实际上是一个组合注解,定义如下:

这个注解由三个注解组成。
①第一个@Spring BootConfiguration的定义如下:

原来就是一个@Configuration,所以@Spring BootConfiguration的功能就是表明这是一个配置类,开发者可以在这个类中配置Bean。从这个角度来讲,这个类所扮演的角色有点类似于Spring中applicationContext.xml文件的角色。
②第二个注解@EnableAutoConfiguration表示开启自动化配置。Spring Boot中的自动化配置是非侵入式的,在任意时刻,开发者都可以使用自定义配置代替自动化配置中的某一个配置。
③第三个注解@ComponentScan完成包扫描,也是Spring中的功能。由于@ComponentScan注解默认扫描的类都位于当前类所在包的下面,因此建议在实际项目开发中把项目启动类放在根包中,如图2-1所示。

图2-1
虽然项目的启动类也包含@Configuration注解,但是开发者可以创建一个新的类专门用来配置Bean,这样便于配置的管理。这个类只需要加上@Configuration注解即可,代码如下:

项目启动类中的@ComponentScan注解,除了扫描@Service、@Repository、@Component、@Controller和@RestController等之外,也会扫描@Configuration注解的类。