常用注解
约 269 字小于 1 分钟
2026-05-11
@SpringBootApplication
@SpringBootApplication 是 Spring Boot 项目的启动类注解,是 Spring Boot 应用的主配置类和入口类。Spring Boot 会运行这个类的 main 方法来启动整个应用。
@SpringBootApplication本质上是一个组合注解,是 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan 的组合。
@SpringBootConfiguration:包含了@Configuration注解,表示该类是一个配置类,可以定义 Bean 并加载到 Spring 容器中。@EnableAutoConfiguration:启用自动配置,Spring Boot 会根据当前项目的依赖关系,自动配置 Spring 容器中的 Bean。@ComponentScan:自动扫描并注册指定包及其子包中的组件,例如@Component、@Service、@Repository和@Controller`。
@ComponentScan
@ComponentScan 包含于 @SpringBootApplication 注解中,通常不需要额外添加 @ComponentScan 注解。 如果需要的 Controller 与 @SpringBootApplication 所在的包不一致,可以通过 @ComponentScan 注解指定扫描的包。
例如 stuController 不在主应用类的包及子包里,则需要在主应用类添加 @ComponentScan("com.example") 注解,让 Soring 容器能够扫描到 stuController。
com.example
demo1
service
UserService.java
controller
UserController.java
mapper
UserMapper.java
Demo1Application.java# 主应用类
stuController
StuController.java