springboot的基础要点
Spring Boot 的核心设计理念是 "约定优于配置"(Convention Over Configuration),旨在简化 Spring 应用的初始搭建和开发过程。以下是需要掌握的核心基础要点:
一、核心机制
自动配置 (Auto-Configuration)
- 通过
spring-boot-autoconfigure
自动配置 Bean - 条件注解控制:
@ConditionalOnClass
,@ConditionalOnMissingBean
等 - 查看自动配置报告:启动时添加
--debug
参数
- 通过
起步依赖 (Starter Dependencies)
- 一站式引入相关技术栈(如
spring-boot-starter-web
包含 Web+Tomcat+JSON) - 避免版本冲突(由 Spring Boot 统一管理)
- 一站式引入相关技术栈(如
二、核心注解
注解 | 作用 |
---|---|
@SpringBootApplication | 复合注解:@Configuration + @ComponentScan + @EnableAutoConfiguration |
@RestController | 等价于 @Controller + @ResponseBody |
@ConfigurationProperties | 将配置文件绑定到 Java 对象(如 application.yml 中的属性) |
@EnableConfigurationProperties | 启用配置绑定 |
三、配置文件
优先级(从高到低):
命令行参数 > 外部配置文件 > 内部配置文件
- 内部配置文件:
application.properties
>application.yml
- 外部配置文件:Jar 包同级目录的
/config
文件夹 > 根目录
- 内部配置文件:
多环境配置
# application-dev.yml server:port: 8081 --- # application-prod.yml server:port: 80
- 激活环境:
spring.profiles.active=dev
- 激活环境:
四、常用功能组件
数据访问
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
- 无需配置数据源:默认使用内存数据库(H2)
- 自定义数据源:
spring.datasource.url=jdbc:mysql:///test
Web MVC
- 静态资源路径:
/static
,/public
,/resources
,/META-INF/resources
- 拦截器配置:
@Override public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/api/**"); }
- 静态资源路径:
事务管理
@Transactional // 直接在 Service 层添加注解 public void updateUser(User user) {userRepository.save(user);logRepository.insertLog(user); }
五、运维监控
Actuator 健康检查
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- 暴露端点:
management.endpoints.web.exposure.include=health,info,metrics
- 访问:
http://localhost:8080/actuator/health
- 暴露端点:
日志配置
# application.properties logging.level.root=INFO logging.level.com.example.service=DEBUG logging.file.name=app.log
六、最佳实践
目录结构规范
src/main/java└─ com.example├─ Application.java # 主启动类├─ controller├─ service├─ repository└─ config
全局异常处理
@ControllerAdvice public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception ex) {return ResponseEntity.status(500).body("服务器开小差了");} }
热部署技巧
<!-- spring-boot-devtools 依赖 --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional> </dependency>
- 修改代码后自动重启(IDEA 需开启
Build > Compiler > Build project automatically
)
- 修改代码后自动重启(IDEA 需开启
七、调试技巧
- 查看自动配置列表
java -jar your-app.jar --debug
- Bean 依赖关系图
@SpringBootApplication public class Application {public static void main(String[] args) {// 启动时打印Bean图new SpringApplicationBuilder(Application.class).logStartupInfo(true).run(args);} }
避坑指南:
- 避免使用
@Autowired
注入静态变量(使用 setter 注入) - 不要在主类中写业务逻辑(保持为纯启动入口)
- 多环境配置务必关闭
spring.config.use-delimiter
(防止YAML解析错误)
终极建议:理解自动配置原理比死记配置更重要,遇到问题时查看
spring-boot-autoconfigure
源码。掌握基础后,再配合之前的"骚操作",可大幅提升开发效率!