在使用 Spring Boot 的过程中,工程师经常会遇到一些典型问题。以下是一些常见问题及其解决方案,涵盖配置、依赖、启动、数据库连接、日志等多个方面:
- 启动失败:端口被占用
现象:
应用启动时报错 Web server failed to start. Port XXXX was already in use.
原因:
默认端口(如 8080)已被其他进程占用。
解决方案:
修改 application.properties 或 application.yml 中的端口:
server.port=8081
查找并终止占用端口的进程(Linux/macOS):
lsof -i :8080
kill -9
- 依赖冲突或版本不兼容
现象:
运行时报 NoSuchMethodError、ClassNotFoundException 等。
原因:
不同依赖引入了不同版本的相同库(如 Jackson、Hibernate)。
解决方案:
使用 mvn dependency:tree(Maven)或 ./gradlew dependencies(Gradle)分析依赖树。
在 pom.xml 中排除冲突依赖:
com.fasterxml.jackson.core
jackson-databind
尽量使用 Spring Boot 官方提供的 starter,避免手动指定版本。
- 数据库连接失败
现象:
启动时报 Cannot determine embedded database driver class for database type NONE 或连接超时。
原因:
未正确配置数据源;
未添加数据库驱动依赖;
数据库服务未启动。
解决方案:
确保 application.properties 配置正确:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
添加对应驱动依赖(如 MySQL):
mysql
mysql-connector-java
runtime
- 静态资源无法访问(404)
现象:
访问 /static/css/style.css 返回 404。
原因:
Spring Boot 默认只从特定目录提供静态资源(/static, /public, /resources, /META-INF/resources)。
解决方案:
确保文件放在 src/main/resources/static/ 下;
若需自定义路径,可配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/custom/**")
.addResourceLocations("file:/path/to/custom/");
}
}
- 跨域问题(CORS)
现象:
前端调用后端接口时浏览器报 CORS 错误。
解决方案:
全局配置(推荐):
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
config.setAllowedMethods(Arrays.asList(""));
config.setAllowedHeaders(Arrays.asList(" "));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
或在 Controller 上加注解(仅限测试):
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class MyController { ... }
- 日志输出混乱或级别不对
现象:
日志太多/太少,或格式不符合预期。
解决方案:
Spring Boot 默认使用 Logback。可通过 application.properties 调整日志级别:
logging.level.com.example=DEBUG
logging.level.org.springframework=WARN
自定义 logback-spring.xml 放在 src/main/resources 下以实现高级配置。
- @Autowired 失效或 Bean 找不到
现象:
Field xxx in com.example.Xxx required a bean of type 'Yyy' that could not be found.
原因:
类未被 Spring 扫描到;
缺少 @Component、@Service、@Repository 等注解;
包结构不在主启动类所在包或其子包下。
解决方案:
确保主启动类上有 @SpringBootApplication(它包含 @ComponentScan);
若 Bean 在外部包,显式指定扫描路径:
@SpringBootApplication(scanBasePackages = {"com.example", "com.external"})
对于第三方类,使用 @Bean 在配置类中手动注册。
- 打包后无法运行(Fat Jar 问题)
现象:
java -jar app.jar 报错 no main manifest attribute。
原因:
未使用 Spring Boot 的 Maven/Gradle 插件打包。
解决方案:
Maven 项目确保有:
org.springframework.boot
spring-boot-maven-plugin
Gradle 项目添加:
plugins {
id 'org.springframework.boot' version '3.x.x'
}
- Actuator 端点未暴露或权限问题
现象:
访问 /actuator/health 返回 404 或 401。
解决方案:
暴露所需端点:
management.endpoints.web.exposure.include=health,info,metrics
若使用 Spring Security,需放行 Actuator 路径:
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}
- 热部署不生效(DevTools)
现象:
修改代码后未自动重启。
解决方案:
确保添加了依赖:
org.springframework.boot
spring-boot-devtools
true
IDE 设置:启用"Build project automatically"(IntelliJ:Settings → Build → Compiler → Build project automatically);
对于 IntelliJ,还需开启 Allow auto-make to start even if developed application is currently running