SpringBoot 超详细(入门 + 实战 + 面试)2026年

📅 2026/7/25 13:52:56
SpringBoot 超详细(入门 + 实战 + 面试)2026年
从零基础入门到项目实战再到核心原理剖析和面试高频题一文全覆盖。--- 一、入门篇从零开始掌握 Spring Boot1.1 什么是 Spring BootSpring Boot 是 Spring 家族中的一站式快速开发框架它的核心思想是约定大于配置。你不再需要手动配置 XML、部署到外部 Tomcat而是通过自动配置、起步依赖Starter、嵌入式服务器极速创建独立的、生产级的 Spring 应用。关键优势· 快速构建使用 Initializr 几秒生成项目骨架。· 简化依赖spring-boot-starter-* 一键整合技术栈。· 自动配置根据类路径中的 Jar 包自动配置 Bean。· 内嵌服务器内置 Tomcat、Jetty、Undertow直接 java -jar 运行。· 运维友好提供 Actuator 健康检查、指标监控、外部化配置。1.2 环境准备· JDKSpring Boot 2.x 需要 JDK 83.x 需要 JDK 17。· 构建工具Maven推荐 3.5或 Gradle。· IDEIntelliJ IDEA旗舰版对 Spring 支持极佳、Eclipse。1.3 第一个 Spring Boot 应用Hello World方式一在线创建最快访问 https://start.spring.io选择Maven、Java、Spring Boot 版本添加 Spring Web 依赖点击生成并下载解压后用 IDEA 打开。方式二IDEA 内创建File - New - Project - Spring Initializr同样勾选 Spring Web。项目目录结构textsrc├── main│ ├── java/com/example/demo│ │ └── DemoApplication.java (启动类)│ └── resources│ ├── static (静态资源)│ ├── templates (模板文件)│ └── application.properties (配置文件)└── test在包下新建 controller 文件夹创建 HelloController.javajavapackage com.example.demo.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;RestControllerpublic class HelloController {GetMapping(/hello)public String hello() {return Hello, Spring Boot!;}}运行 DemoApplication 的 main 方法访问 http://localhost:8080/hello看到输出即成功。1.4 项目结构解析与核心注解· 主启动类必须放在业务包的最外层如 com.example.demo因为它内含 SpringBootApplication 注解该注解组合了· SpringBootConfiguration标记为配置类。· EnableAutoConfiguration开启自动配置的魔法。· ComponentScan开启组件扫描会扫描主类所在包及子包下的所有 Component、Service、Controller 等。· application.properties/yml一切配置的入口支持属性绑定、多环境切换。1.5 配置文件详解YAML 语法更简洁推荐使用。 支持 profile 多环境配置。yaml# application-dev.ymlserver:port: 8081# application-prod.ymlserver:port: 80在主配置文件中指定激活的环境yamlspring:profiles:active: dev属性绑定可将配置直接映射到 POJO。javaComponentConfigurationProperties(prefix app)public class AppConfig {private String name;private String version;// getter/setter...}yamlapp:name: MyAppversion: 1.0.01.6 常用 Starter 介绍· spring-boot-starter-webWeb 开发内嵌 TomcatSpring MVC· spring-boot-starter-data-jpa / mybatis-spring-boot-starter数据库操作· spring-boot-starter-data-redisRedis 集成· spring-boot-starter-security安全认证· spring-boot-starter-test测试框架· spring-boot-starter-actuator应用监控--- 二、实战篇构建一个生产级 RESTful 应用我们以“用户管理系统”为例手把手整合常见技术。2.1 RESTful API 与统一响应定义统一的响应体javapublic class ResultT {private int code;private String message;private T data;// 构造器、静态成功/失败方法...public static T ResultT success(T data) {return new Result(200, success, data);}public static T ResultT error(int code, String msg) {return new Result(code, msg, null);}}创建实体类 User并编写 UserControllerjavaRestControllerRequestMapping(/api/users)public class UserController {Autowiredprivate UserService userService;GetMapping(/{id})public ResultUser getUser(PathVariable Long id) {return Result.success(userService.getById(id));}PostMappingpublic ResultVoid create(Validated RequestBody User user) {userService.save(user);return Result.success(null);}}2.2 参数校验使用 hibernate-validator已内置在 web starter 中。javapublic class User {private Long id;NotBlank(message 姓名不能为空)private String name;Email(message 邮箱格式不正确)private String email;// ...}使用 Validated 开启校验结合全局异常处理捕获校验失败信息。2.3 全局异常处理利用 RestControllerAdvice 统一处理异常避免把错误堆栈直接返回给前端。javaRestControllerAdvicepublic class GlobalExceptionHandler {// 处理参数校验异常ExceptionHandler(MethodArgumentNotValidException.class)public ResultVoid handleValidException(MethodArgumentNotValidException e) {String msg e.getBindingResult().getFieldError().getDefaultMessage();return Result.error(400, msg);}// 处理自定义业务异常ExceptionHandler(BusinessException.class)public ResultVoid handleBusinessException(BusinessException e) {return Result.error(e.getCode(), e.getMessage());}// 兜底处理ExceptionHandler(Exception.class)public ResultVoid handleException(Exception e) {return Result.error(500, 服务器内部错误);}}2.4 数据访问层整合 MyBatis-Plus引入依赖xmldependencygroupIdcom.baomidou/groupIdartifactIdmybatis-plus-boot-starter/artifactIdversion最新版/version/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactId/dependency配置数据源yamlspring:datasource:url: jdbc:mysql://localhost:3306/test?useSSLfalseserverTimezoneUTCusername: rootpassword: 123456mybatis-plus:mapper-locations: classpath:/mapper/*.xmlconfiguration:map-underscore-to-camel-case: true编写 Mapper 接口javaMapperpublic interface UserMapper extends BaseMapperUser {// 自定义复杂查询可写在对应的 XML 中}Service 层直接使用 MyBatis-Plus 的 IService 和 ServiceImpl 可快速实现 CRUD配合分页插件实现物理分页。2.5 缓存整合 Redis引入 spring-boot-starter-data-redis配置连接yamlspring:redis:host: localhostport: 6379直接注入 StringRedisTemplate 或 RedisTemplate 操作缓存。更优雅的方式是使用 Spring Cache 抽象在 Service 上加 Cacheable 等注解底层用 Redis 实现。2.6 定时与异步任务定时任务启动类加 EnableScheduling方法上加 Scheduled(cron 0 0/5 * * * ?) 每隔5分钟执行。异步任务启动类加 EnableAsync方法上加 Async会自动从线程池中分配线程执行避免阻塞主线程。2.7 拦截器与过滤器过滤器Filter处于最外层处理请求编码、安全过滤属于 Servlet 范畴。拦截器InterceptorSpring 层面可以拿到 Handler 方法信息常用于登录鉴权、日志记录。实现 HandlerInterceptor并注册到 WebMvcConfigurer 中javaConfigurationpublic class WebConfig implements WebMvcConfigurer {Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new AuthInterceptor()).addPathPatterns(/api/**).excludePathPatterns(/api/login);}}2.8 跨域配置· 局部直接在 Controller 或方法上加 CrossOrigin 注解。· 全局在 WebMvcConfigurer 中重写 addCorsMappings。javaOverridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/**).allowedOriginPatterns(*).allowedMethods(GET,POST,PUT,DELETE).allowCredentials(true);}2.9 文件上传Controller 接收 MultipartFile 类型参数配置文件中可限制大小yamlspring:servlet:multipart:max-file-size: 10MBmax-request-size: 100MB2.10 测试Spring Boot 提供了强大的测试支持javaSpringBootTestAutoConfigureMockMvcclass UserControllerTest {Autowiredprivate MockMvc mockMvc;Testvoid testGetUser() throws Exception {mockMvc.perform(get(/api/users/1)).andExpect(status().isOk()).andExpect(jsonPath($.data.name).value(张三));}}---⚙️ 三、原理篇深挖“自动配置”的魔法3.1 自动配置的核心流程自动配置的秘密全在 SpringBootApplication 中的 EnableAutoConfiguration它通过 Import(AutoConfigurationImportSelector.class) 导入选择器。运行流程1. AutoConfigurationImportSelector 会执行 selectImports 方法。2. 调用 SpringFactoriesLoader 从所有依赖的 META-INF/spring.factories 文件Spring Boot 2.x或 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件Spring Boot 2.7及3.x中读取 org.springframework.boot.autoconfigure.EnableAutoConfiguration 键对应的所有配置类全限定名。3. 得到一份完整的候选自动配置类列表如 DataSourceAutoConfiguration、WebMvcAutoConfiguration 等。4. 对这些类进行条件过滤检查 ConditionalOnClass类是否存在、ConditionalOnMissingBean容器中是否已有、ConditionalOnProperty配置项是否匹配等。5. 保留所有通过条件筛选的配置类并将它们导入 IOC 容器完成 Bean 的注册。3.2 案例数据源自动配置看一下 DataSourceAutoConfiguration 的部分代码逻辑javaConfigurationConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})EnableConfigurationProperties(DataSourceProperties.class)public class DataSourceAutoConfiguration {BeanConditionalOnMissingBeanpublic DataSource dataSource(DataSourceProperties properties) {// 根据配置属性创建 HikariCP 数据源return properties.initializeDataSourceBuilder().build();}}它会检查类路径下有数据源相关类且用户没有自定义 DataSource Bean才会自动创建默认的 HikariCP 数据源并用我们在 application.yml 里写的 spring.datasource 属性进行填充。3.3 Spring Boot 启动流程简述SpringApplication.run() 主要干了这几件大事1. 创建 SpringApplication推断 Web 应用类型SERVLET/REACTIVE加载初始化器和监听器找到主配置类。2. 发布启动事件通过 SpringApplicationRunListener 广播 starting 事件。3. 准备环境创建并配置 Environment加载所有外部化配置源广播 environmentPrepared 事件。4. 创建容器根据 Web 类型创建 AnnotationConfigServletWebServerApplicationContext。5. 准备容器后置处理 ApplicationContext执行所有的 ApplicationContextInitializer加载主配置类为 Bean 定义广播 contextPrepared、contextLoaded 事件。6. 刷新容器调用 refresh()这是 Spring 的核心步骤扫描、实例化所有单例 Bean自动配置就发生在此阶段。同时会启动内嵌的 Web 服务器。7. 完成启动广播 started 事件调用 ApplicationRunner 和 CommandLineRunner。8. 等待服务Web 服务器进入监听状态广播 ready 事件应用正式对外服务。3.4 嵌入式服务器原理以 Tomcat 为例ServletWebServerApplicationContext 在 refresh() 时会调用 createWebServer()。它会从容器中获取 ServletWebServerFactory Bean由 TomcatServletWebServerFactoryAutoConfiguration 自动配置提供然后调用 getWebServer 创建并初始化 Tomcat 实例最后启动它监听我们配置的端口。3.5 自定义 Starter掌握自定义 Starter 是理解自动配置的进阶应用。以开发一个“短信服务 Starter”为例1. 创建 sms-spring-boot-starter 项目只放 pom.xml引入 sms-spring-boot-autoconfigure。2. 创建 sms-spring-boot-autoconfigure 模块· 编写配置属性类 SmsProperties用 ConfigurationProperties(prefix sms) 绑定配置。· 编写核心服务类 SmsService。· 编写自动配置类 SmsAutoConfigurationjavaConfigurationEnableConfigurationProperties(SmsProperties.class)ConditionalOnClass(SmsService.class)public class SmsAutoConfiguration {BeanConditionalOnMissingBeanpublic SmsService smsService(SmsProperties properties) {return new SmsService(properties);}}· 在 resources/META-INF/spring/ 下新建文件 org.springframework.boot.autoconfigure.AutoConfiguration.imports写入自动配置类的全限定名com.example.sms.SmsAutoConfiguration。3. 打包发布后其他项目引入你的 Starter在 application.yml 中配置 sms 开头的属性即可直接注入 SmsService 使用。3.6 Actuator 监控原理Actuator 通过引入一系列的Endpoint端点来暴露应用信息。核心是 EndpointDiscoverer 会扫描所有 Endpoint 注解的 Bean然后通过 JMX 或 HTTP 暴露出来。HealthEndpoint 会聚合所有 HealthIndicator 的健康状态MetricsEndpoint 则依赖 Micrometer 收集指标数据。--- 四、面试篇高频面试题精解Q1Spring Boot 的自动配置是如何实现的A 启动类上的 SpringBootApplication 包含了 EnableAutoConfiguration该注解通过 Import 导入了 AutoConfigurationImportSelector。它会从所有依赖包的 spring.factories 或 auto-configuration.imports 文件中加载候选的自动配置类并根据 Conditional 系列注解如 ConditionalOnClass进行条件过滤最终将满足条件的配置类注入到 IOC 容器完成 Bean 的自动装配。Q2说说 Spring Boot 的启动流程。A 1. 创建 SpringApplication初始化监听器。2. 发布 Starting 事件。3. 构建 Environment加载配置。4. 创建 ApplicationContext。5. 准备 Context注册主配置类、执行初始化器。6. 调用 refresh() 刷新容器这是 Spring 的核心会完成 Bean 的扫描、自动配置、启动内嵌 Web 服务器。7. 发布 Started 事件调用 Runner。8. 发布 Ready 事件应用启动完成。Q3如何排除某个自动配置类A 三种方式1. 注解属性排除SpringBootApplication(exclude DataSourceAutoConfiguration.class)2. 配置文件排除spring.autoconfigure.excludeorg...DataSourceAutoConfiguration3. 条件装配自定义同类型 BeanConditionalOnMissingBean 会让自动配置失效。Q4配置文件加载的优先级顺序是怎样的A 优先级从高到低为· 命令行参数--server.port8080· 操作系统环境变量· Jar 包外部的 application-{profile}.yml/properties· Jar 包外部的 application.yml/properties· Jar 包内部的 application-{profile}.yml/properties· Jar 包内部的 application.yml/properties· PropertySource 引入的文件Q5如何处理全局异常A 使用 RestControllerAdvice 或 ControllerAdvice 配合 ExceptionHandler 方法。可以针对不同异常类型如业务异常、校验异常进行捕获并返回统一格式的响应体避免暴露服务器内部细节。Q6拦截器和过滤器的区别是什么A· 过滤器基于 Servlet 规范由 Servlet 容器回调可以过滤所有请求包括静态资源。主要用于编码处理、请求过滤。· 拦截器基于 Spring 的 HandlerInterceptor由 Spring MVC 框架管理。可以访问 Spring 上下文中的 Bean能够获取到被调用的 Handler 方法信息常用于登录鉴权、日志记录。拦截器是在 DispatcherServlet 之后Controller 之前调用的。Q7如何自定义一个 StarterA 1. 创建一个 xxx-spring-boot-autoconfigure 模块编写核心服务类和自动配置类Configuration Conditional...。2. 在 resources/META-INF/spring/ 下创建 org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件注册自动配置类。3. 创建一个空的 xxx-spring-boot-starter 模块依赖上述自动配置模块。4. 使用者引入 Starter 后通过配置文件 ConfigurationProperties 绑定参数即可直接使用。Q8Spring Boot 有哪些方式可以实现热部署A 主要使用 spring-boot-devtools它利用了双类加载器机制。应用类加载器加载我们写的代码基础类加载器加载不变的第三方库。当代码变更时它只重启应用类加载器所以速度快很多。生产环境必须禁用。Q9Bean 的生命周期是怎样的A 实例化 → 属性填充 → 调用各种 Aware 接口 → BeanPostProcessor 前置处理 → 初始化方法PostConstruct、InitializingBean→ BeanPostProcessor 后置处理 → 就绪使用 → 销毁前调用 PreDestroy 或 DisposableBean。Q10如何保证 Spring Boot 应用的线程安全A 核心是保持 Controller、Service、Dao 等 Bean 无状态的。默认情况下Spring 管理的 Bean 都是单例的如果定义了共享的可变成员变量就会有线程安全问题。应把状态信息限定在方法内部或使用 ThreadLocal 来隔离线程数据。---这份全解基本覆盖了 Spring Boot 从入门到进阶的全路径建议按篇章顺序学习并手敲每一个实战代码原理部分结合源码去理解面试题在理解的基础上记忆。祝你掌握 Spring Boot 这个利器