Spring Boot:
一、Spring Boot 核心特性
自动配置
根据类路径中的依赖自动配置 Bean(如 spring-boot-starter-web 自动配置 Tomcat)。
通过 @EnableAutoConfiguration 或 @SpringBootApplication 启用。
起步依赖
预定义的依赖组合(如 spring-boot-starter-data-jpa 包含 JPA + Hibernate)。
简化依赖管理,避免版本冲突。
嵌入式容器
默认集成 Tomcat,无需手动部署 WAR 包。
支持切换为 Jetty 或 Undertow。
外部化配置
通过 application.properties 或 application.yml 配置参数。
支持多环境配置(如 application-dev.properties)。
Actuator(监控与管理)
提供端点(Endpoints)监控应用健康、指标、日志等(如 /actuator/health)。
需添加 spring-boot-starter-actuator 依赖。
二、核心注解与组件
启动类注解
@SpringBootApplication:组合了 @Configuration、@EnableAutoConfiguration 和 @ComponentScan。
Bean 管理
@Component、@Service、@Repository、@Controller:定义 Bean。
@Autowired:自动注入依赖。
配置类
@Configuration:标记配置类。
@Bean:声明方法返回的 Bean。
条件注解
@ConditionalOnClass、@ConditionalOnProperty:根据条件启用配置。
三、常用模块
-
Web 开发
RESTful API:使用 @RestController 和 @GetMapping/@PostMapping 等注解。
参数传递:@PathVariable、@RequestParam、@RequestBody。
静态资源处理:resources/static 目录存放静态文件。
模板引擎:Thymeleaf、Freemarker(需配置 spring-boot-starter-thymeleaf)。 -
数据访问
Spring Data JPA:
使用 @Entity 定义实体类,@Repository 接口继承 JpaRepository。
简化 CRUD 操作。
MyBatis:需整合 mybatis-spring-boot-starter,通过 @Mapper 注解接口。
事务管理:@Transactional 注解声明事务。 -
配置管理
多环境配置:
application.properties
spring.profiles.active=dev
创建 application-dev.properties、application-prod.properties。
自定义配置:
application.yml
custom:
api-key: 123456
通过 @Value("${custom.api-key}") 或 @ConfigurationProperties 注入。