Spring Boot 默认不包含 web 依赖,需手动勾选“Spring Web”才能添加 spring-boot-starter-web,否则无嵌入式容器、DispatcherServlet 不加载、@RestController 不生效,JDK 17+ 还可能因缺少 jakarta.servlet 编译失败。

用 Spring Initializr 创建项目时,为什么生成的 pom.xml 里没有 spring-boot-starter-web?
因为默认模板只加了最基础的 spring-boot-starter,不带任何 Web 能力。你要手动勾选 “Spring Web” 才会注入 spring-boot-starter-web —— 这不是 bug,是设计:Spring Boot 默认不假设你写 Web 应用。
常见错误现象:Application 能启动,但访问 http://localhost:8080 直接 404,控制台也没打印 Tomcat 启动日志;@RestController 类完全不生效。
- 使用场景:新建空项目后想立刻写接口,却连 DispatcherServlet 都没加载
- 参数差异:在 start.spring.io 页面,务必勾选 “Spring Web”,否则生成的依赖不含嵌入式容器和 MVC 自动配置
- 兼容性影响:JDK 17+ 项目若漏掉 Web Starter,还会因缺少
jakarta.servlet导致编译失败(报错package jakarta.servlet does not exist)
@SpringBootApplication 到底做了哪三件事?
它只是个组合注解,等价于 @Configuration + @EnableAutoConfiguration + @ComponentScan。真正让“零配置启动”成立的,是后两者。
容易踩的坑:有人把主类放到 com.example.util 这类非根包下,导致 @ComponentScan 扫不到 @Service 或 @Repository 类——默认只扫主类所在包及其子包。
立即学习“Java免费学习笔记(深入)”;
- 使用场景:新增一个
@Service类,但运行时报No qualifying bean of type 'XxxService' - 性能影响:如果主类放在很深的包路径(如
com.a.b.c.d.e.Application),@ComponentScan会递归扫描所有子包,启动稍慢(通常可忽略,但大项目要注意) - 自动装配原理的关键点:
@EnableAutoConfiguration会读取META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(Spring Boot 2.7+),而不是旧版的spring.factories;这个文件列出了所有条件化加载的自动配置类
为什么加了 spring-boot-devtools 却热更新不生效?
因为 IDE 编译行为和 DevTools 的监听机制不匹配。DevTools 默认只监听 classpath:/static、/templates 和 /public 下的资源变更,Java 类修改后需触发重新编译并重启 JVM —— 它本身不提供字节码热替换(JVM 级)。
常见错误现象:改了 @Controller 方法内容,保存后刷新页面没变化;IDE 显示编译成功,但控制台没打印 “Restarting” 字样。
- 实操建议:IntelliJ 用户需开启
Build project automatically,并按Ctrl+Shift+Alt+/打开 Registry,勾选compiler.automake.allow.when.app.running - 使用场景:日常开发中频繁改 Controller/Service,期望保存即生效
- 注意:Maven 构建的 jar 包运行时,
devtools会被自动禁用(通过spring.devtools.restart.enabled=false)
application.yml 中的 spring.profiles.active 为什么有时不生效?
优先级问题。它会被命令行参数、环境变量、JVM 参数覆盖。比如你在 IDEA 的 Run Configuration 里写了 -Dspring.profiles.active=prod,那 yml 里的设置就完全被无视。
最容易被忽略的一点:profile 激活名大小写敏感,active: DEV 和 active: dev 是两个不同 profile,而多数 starter(如 spring-boot-starter-jdbc)只认小写 dev。
- 实操建议:启动时加
--debug参数,看控制台输出的 “Active profiles” 是否符合预期;或打印Environment.getActiveProfiles()验证 - 使用场景:本地开发用
dev,测试环境用test,但切换后数据库连接还是连向生产库 - 兼容性影响:Spring Boot 3.x 开始,
spring.profiles.active不再支持逗号分隔多个值(如dev,mysql),必须用 YAML 数组语法:spring.profiles.active: [dev, mysql]
自动装配不是魔法,它靠的是约定路径、固定命名、条件注解(@ConditionalOnClass、@ConditionalOnMissingBean)和导入顺序。最常出问题的地方,其实是 classpath 混乱——比如同时引入了 Spring Boot 2.x 和 3.x 的 starter,或者自己手写了一个同名 AutoConfiguration 类却没加 @Conditional 控制加载时机。










