错误现象:
java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotationUtils.isAnnotationInherited
原因分析:
不同版本的Spring组件冲突(如同时存在Spring Boot 2.3和2.5的依赖)。
解决方案:
Maven项目:运行依赖树分析命令定位冲突:
1 |
mvn dependency:tree -Dverbose | grep conflict |
Gradle项目:执行依赖报告:
1 |
gradle dependencies > dep.txt |
在pom.xml或build.gradle中显式声明版本号,使用<exclusions>排除旧依赖。
防坑技巧:
使用IDE插件(如IntelliJ的Maven Helper、VS Code的Gradle Lens)可视化分析依赖树。
错误现象:
No qualifying bean of type 'com.example.UserService' available
原因分析:
解决方案:
代码示例:
1 2 3 |
@SpringBootApplication @ComponentScan(basePackages = "com.example") // 显式指定扫描路径 public class Application { ... } |
错误现象:
WebServerException: Unable to start embedded Tomcat (Port 8080 already in use)
解决方案:
终止占用进程:
1 2 3 4 |
# Linux/Mac lsof -i :8080 && kill -9 <PID> # Windows netstat -ano | findstr 8080 && taskkill /F /PID <PID> |
修改应用端口:
1 2 3 |
# application.yml server: port: 8081 |
随机端口(适合测试环境):
1 2 |
server: port: 0 |
错误现象:
配置属性未生效,日志无报错。
原因分析:
解决方案:
开启配置属性调试:
1 2 3 |
logging: level: org.springframework.boot.context.properties: TRACE |
错误现象:
HikariPool-1 - Exception during pool initialization: Connection refused
原因分析:
数据库URL、用户名或密码错误。
数据库服务未启动。
连接池配置超时时间过短。
解决方案:
检查application.yml中的数据库配置:
1 2 3 4 5 |
spring: datasource: url: jdbc:mysql://localhost:3306/mydb?useSSL=false username: root password: root |
增加连接池超时时间:
1 2 3 4 |
spring: datasource: hikari: connection-timeout: 30000 |
错误现象:
Error: Unable to find or load main class com.example.Application
解决方案:
Maven项目:检查pom.xml中是否配置了主类:
1 2 3 |
<properties> <start-class>com.example.Application</start-class> </properties> |
Gradle项目:在build.gradle中指定主类:
1 2 3 |
springBoot { mainClass = 'com.example.Application' } |
重新生成IDE项目文件(如执行mvn idea:idea或gradle idea)。
错误现象:
BeanCurrentlyInCreationException: Error creating bean with name 'A'
解决方案:
优先使用构造器注入:避免字段注入导致循环依赖。
延迟加载:在其中一个Bean上添加@Lazy注解。
终极方案:重构代码,提取公共逻辑到第三方类。
代码示例:
1 2 3 4 5 6 7 |
@Service public class ServiceA { private final ServiceB serviceB; public ServiceA(@Lazy ServiceB serviceB) { this.serviceB = serviceB; } } |
错误现象:
java.lang.ClassNotFoundException: org.apache.commons.lang3.StringUtils
解决方案:
检查依赖是否缺失:
1 2 3 4 5 6 |
<!-- Maven示例 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> |
使用mvn clean install -U强制更新依赖。
检查是否有<scope>provided</scope>错误配置。
错误现象:
RedisConnectionFailureException: Unable to connect to Redis
解决方案:
检查Redis服务是否启动:
1 |
redis-cli ping # 返回PONG表示正常 |
确认配置文件中的Redis连接信息:
1 2 3 4 5 |
spring: redis: host: localhost port: 6379 password: 123456 |
防坑技巧:
使用Spring Boot官方提供的依赖管理:
1 2 3 4 5 6 7 8 9 10 11 |
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>3.1.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> |
错误现象:
访问静态资源(如HTML、JS)时返回Spring Boot默认错误页。
原因分析:
静态资源未放在src/main/resources/static或public目录。
自定义拦截器(如Spring Security)拦截了静态请求。
未配置欢迎页(index.html优先级低于控制器路由)。
解决方案:
检查资源路径是否符合规范:
src/main/resources/
├── static/
│ └── index.html
└── public/
└── logo.png
若使用Spring Security,放行静态资源:
1 2 3 4 5 6 7 8 |
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/static/**", "/public/**").permitAll(); } } |
防坑技巧:
优先使用classpath:/static/存放资源,避免路径混淆。
错误现象:
No active profile set, falling back to default profiles: default
原因分析:
未通过启动参数、环境变量或配置文件激活Profile。
application-{profile}.yml文件命名错误。
解决方案:
命令行激活:
1 |
java -jar app.jar --spring.profiles.active=prod |
环境变量激活:
1 |
export SPRING_PROFILES_ACTIVE=dev && java -jar app.jar |
配置文件硬编码(不推荐生产环境):
1 2 3 4 |
# application.yml spring: profiles: active: dev |
防坑技巧:
生产环境禁止在配置文件中硬编码active,推荐使用外部化配置(如Kubernetes ConfigMap)。
错误现象:
BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'com.example.UserService' but was actually of type 'jdk.proxy2.$Proxy123'
原因分析:
JDK动态代理生成的代理类与原始类类型不兼容。
目标类未实现接口,但强制使用了JDK代理。
解决方案:
强制使用CGLIB代理(修改配置):
1 2 3 4 |
# application.yml spring: aop: proxy-target-class: true |
目标类实现一个空接口(兼容JDK代理)。
代码示例:
1 2 3 4 |
public interface UserServiceInterface {}
@Service public class UserService implements UserServiceInterface { ... } |
错误现象:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/.../logback-classic.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/.../slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
解决方案:
Maven排除冲突依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> |
Gradle排除冲突:
1 2 3 |
configurations.all { exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' } |
错误现象:
1 2 3 |
java.lang.OutOfMemoryError: Java heap space // 或 java.lang.OutOfMemoryError: Metaspace |
紧急处理:
临时扩容:调整JVM参数(示例为堆内存和元空间):
1 |
java -Xmx1024m -Xms512m -XX:MaxMetaspaceSize=256m -jar app.jar |
内存分析:
使用jmap生成堆转储:
1 |
jmap -dump:format=b,file=heapdump.hprof <PID> |
使用VisualVM或Eclipse MAT分析内存泄漏。
防坑技巧:
定期监控生产环境内存使用(如Prometheus + Grafana)。
错误现象:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.example.User
解决方案:
为实体类添加@Getter/@Setter(Lombok)或手动实现getter方法。
忽略未知字段(全局配置):
1 2 3 4 5 |
spring: jackson: default-property-inclusion: non_null deserialization: FAIL_ON_UNKNOWN_PROPERTIES: false |
若使用record类,添加@JsonAutoDetect注解:
1 2 |
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public record User(String name) {} |
错误现象:
请求被拦截返回403 Forbidden或跳转到登录页。
解决方案:
放行公开资源路径:
1 2 3 4 5 6 7 8 |
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login", "/css/**").permitAll() .anyRequest().authenticated() .and() .formLogin(); } |
禁用CSRF(仅限API项目):
1 |
http.csrf().disable(); |
防坑技巧:
生产环境必须启用CSRF保护,仅对无状态API服务可禁用。
错误现象:
@Async方法同步执行,未触发异步线程。
解决方案:
启用异步支持(主类添加注解):
1 2 3 |
@SpringBootApplication @EnableAsync // 关键注解 public class Application { ... } |
自定义线程池(避免默认线程池阻塞):
1 2 3 4 5 6 7 8 9 10 11 12 |
@Configuration public class AsyncConfig { @Bean("taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(200); executor.initialize(); return executor; } } |
调用示例:
1 2 |
@Async("taskExecutor") public void asyncProcess() { ... } |
错误现象:
修改代码后未自动重启。
解决方案:
IDE配置:
添加DevTools依赖:
1 2 3 4 5 6 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> |
排除静态资源重启(提升速度):
1 2 3 4 |
spring: devtools: restart: exclude: static/**,public/** |
错误现象:
应用启动后无任何日志输出。
解决方案:
检查logback-spring.xml或log4j2.xml是否存在配置错误。
强制指定日志级别:
1 2 3 |
logging: level: root: INFO |
添加默认日志依赖:
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> |
原子化验证:每修改一个配置后立即测试,避免多个变更叠加导致问题复杂化。
日志级别控制:遇到问题时将日志级别调整为DEBUG或TRACE:
1 2 3 4 |
logging: level: root: DEBUG org.springframework: TRACE |
最小化复现:提取核心代码到独立Demo项目,排除无关依赖干扰。