外观
Spring Boot 环境设置
约 2675 字大约 9 分钟
2025-08-16
一、项目初始化与基础配置
1. 项目创建方式
Spring Initializr(推荐):
- Web 方式:访问 https://start.spring.io/
- IDEA 集成方式:
- File → New → Project
- 选择 Spring Initializr
- 选择 JDK 版本和 Spring Boot 版本
- 选择需要的依赖(Web, Data JPA, MySQL 等)
- 完成项目创建
Maven 方式:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version> <!-- 使用最新稳定版 -->
<relativePath/> <!-- lookup parent from repository -->
</parent>2. JDK 版本选择
推荐配置:
- 开发环境:JDK 17(当前最广泛使用的 LTS 版本)
- 生产环境:JDK 17 或 JDK 21(最新 LTS)
IDEA 全局 JDK 设置:
- File → Other Settings → Default Project Structure → SDKs → JDK
- 添加并选择合适的 JDK 版本
提示:Spring Boot 3.x 要求 JDK 17 或更高版本,2.x 支持 JDK 8+
3. 项目结构说明
标准 Maven 项目结构:
src
├── main
│ ├── java # Java 源代码
│ ├── resources # 配置文件
│ │ ├── application.properties # 主配置文件
│ │ ├── application-dev.properties # 开发环境配置
│ │ ├── application-test.properties # 测试环境配置
│ │ ├── application-prod.properties # 生产环境配置
│ │ └── static # 静态资源
│ │ └── templates # 模板文件
│ └── resources
└── test
├── java # 测试代码
└── resources # 测试资源配置二、配置文件详解
1. 配置文件格式
两种主要格式:
Properties 格式(application.properties)
server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydbYAML 格式(application.yml) - 推荐
server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver
YAML 优势:
- 层次结构清晰,可读性高
- 支持列表和复杂对象
- 注释更友好
- 缩进表示层级,无需重复键名
提示:YAML 对缩进敏感,必须使用空格(不能使用 Tab),推荐使用 2 空格缩进。
2. 配置文件加载顺序
Spring Boot 配置文件加载顺序(优先级从高到低):
- 命令行参数:
java -jar app.jar --server.port=8081 java:comp/env中的 JNDI 属性- Java 系统属性(
System.getProperties()) - 操作系统环境变量
jar包外部的application-{profile}.properties或.ymljar包内部的application-{profile}.properties或.ymljar包外部的application.properties或.ymljar包内部的application.properties或.yml
提示:配置文件命名必须是
application,否则不会被 Spring Boot 自动识别。
三、多环境配置
1. 多环境配置实现
使用 profile 实现多环境:
# application.yml
spring:
profiles:
active: dev # 激活的环境
---
# application-dev.yml
spring:
profiles: dev
server:
port: 8080
logging:
level:
root: debug
---
# application-test.yml
spring:
profiles: test
server:
port: 9090
logging:
level:
root: info
---
# application-prod.yml
spring:
profiles: prod
server:
port: 80
logging:
level:
root: warn激活指定环境:
- 配置文件:
spring.profiles.active=dev - 命令行参数:
java -jar app.jar --spring.profiles.active=prod - JVM 参数:
java -Dspring.profiles.active=prod -jar app.jar - 环境变量:
export SPRING_PROFILES_ACTIVE=prod
2. 多环境最佳实践
配置策略:
- 公共配置:放在
application.yml中 - 环境特定配置:放在
application-{env}.yml中 - 敏感信息:不要提交到代码仓库,使用环境变量或配置中心
敏感信息处理:
# application-prod.yml
spring:
datasource:
username: ${DB_USER}
password: ${DB_PASSWORD}运行时设置环境变量:
# Linux/Mac
export DB_USER=admin
export DB_PASSWORD=secret
java -jar app.jar
# Windows
set DB_USER=admin
set DB_PASSWORD=secret
java -jar app.jar提示:生产环境绝不应该将敏感信息硬编码在配置文件中,应使用环境变量或配置中心。
四、常用配置项
1. 服务器配置
基本配置:
server:
port: 8080 # 服务端口
servlet:
context-path: /api # 应用上下文路径
tomcat:
max-threads: 200 # Tomcat最大线程数
uri-encoding: UTF-8 # URI编码
connection-timeout: 5000ms # 连接超时SSL 配置(生产环境必需):
server:
ssl:
enabled: true
key-store: classpath:keystore.p12
key-store-password: changeit
key-store-type: PKCS12
key-alias: tomcat2. 日志配置
基本配置:
logging:
level:
root: info
com.example: debug
org.springframework: warn
file:
name: logs/app.log # 日志文件路径
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n"Logback 高级配置: 创建 src/main/resources/logback-spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOGS" value="./logs" />
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>
<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/spring-boot-logger.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天滚动 -->
<FileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!-- 日志最大保留天数 -->
<MaxHistory>30</MaxHistory>
<!-- 按大小滚动 -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<MaxFileSize>10MB</MaxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<root level="info">
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
</root>
</configuration>3. 数据源配置
MySQL 配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 10
connection-timeout: 3000
idle-timeout: 600000
max-lifetime: 1800000连接池选择:
- HikariCP:Spring Boot 2.x 默认,性能最好
- Tomcat JDBC:Spring Boot 1.x 默认
- Commons DBCP2:备选方案
多数据源配置:
spring:
datasource:
primary:
url: jdbc:mysql://localhost:3306/db1
username: root
password: password
type: com.zaxxer.hikari.HikariDataSource
secondary:
url: jdbc:mysql://localhost:3306/db2
username: root
password: password
type: com.zaxxer.hikari.HikariDataSource4. Web 配置
MVC 配置:
spring:
mvc:
favicon:
enabled: false # 禁用favicon
static-path-pattern: /static/** # 静态资源路径
resources:
static-locations: classpath:/static/ # 静态资源位置
http:
encoding:
charset: UTF-8
enabled: true
force: true跨域配置:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000", "https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}五、开发环境优化
1. 热部署配置
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>配置文件(application-dev.yml):
spring:
devtools:
restart:
enabled: true
additional-paths: src/main/java # 监听的额外路径
exclude: static/**,public/** # 排除的路径
livereload:
enabled: true # 浏览器自动刷新IDEA 设置:
- File → Settings → Build, Execution, Deployment → Compiler
- 勾选 "Build project automatically"
- 按 Ctrl+Shift+A 搜索 "Registry"
- 找到 "compiler.automake.allow.when.app.running" 并启用
2. 文件编码设置
全局文件编码:
- File → Other Settings → Default Settings → Editor → File Encodings
- 设置全局编码为 UTF-8
- 设置项目编码为 UTF-8
- 设置属性文件编码为 UTF-8
提示:统一使用 UTF-8 编码可避免中文乱码问题。
3. Maven 配置优化
全局 Maven 设置:
- File → Other Settings → Default Settings → Build & Tools → Maven
- 设置 Maven home directory
- 设置 User settings file(通常为 ~/.m2/settings.xml)
- 配置国内镜像加速
settings.xml 镜像配置:
<mirrors>
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
</mirrors>4. 版本控制配置
Git 配置:
- File → Other Settings → Default Settings → Version Control → Git
- 设置 Path to Git executable(通常自动检测)
- 配置忽略文件(.gitignore)
推荐 .gitignore 内容:
# Maven
target/
# IDE
.idea/
*.iml
.vscode/
*.swp
.DS_Store
# Spring Boot
logs/
*.log
work/
tmp/
*.tmp
# 环境配置
application-local.yml
application-dev.yml六、测试环境配置
1. 测试专用配置
创建测试配置文件:
src/test/resources/application-test.yml
测试配置示例:
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: password
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
h2:
console:
enabled: true2. 测试专用注解
常用测试注解:
@SpringBootTest // 加载完整应用上下文
@DataJpaTest // 仅加载JPA相关配置
@WebMvcTest // 仅加载MVC相关配置
@MockBean // 模拟Bean
@SpyBean // 部分模拟Bean
@TestPropertySource // 自定义测试属性测试配置示例:
@SpringBootTest
@TestPropertySource(locations = "classpath:test-application.properties")
class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void testFindUser() {
// 测试逻辑
}
}七、生产环境配置
1. 安全配置
application-prod.yml 安全配置:
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: never
spring:
security:
user:
name: ${ADMIN_USER:admin}
password: ${ADMIN_PASSWORD}
thymeleaf:
cache: true
server:
compression:
enabled: true
mime-types: text/html,text/css,application/javascript
min-response-size: 10242. 性能优化配置
JVM 参数配置:
java -jar -Xms512m -Xmx512m -XX:MaxMetaspaceSize=256m \
-Dspring.profiles.active=prod \
-Djava.security.egd=file:/dev/./urandom \
app.jar关键配置说明:
-Xms和-Xmx:设置堆内存初始和最大大小-XX:MaxMetaspaceSize:设置元空间大小-Djava.security.egd=file:/dev/./urandom:加快启动速度- 生产环境应关闭 devtools:
-Dspring.devtools.restart.enabled=false
3. 监控配置
添加监控依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>监控配置:
management:
server:
port: 8081 # 监控端口与应用端口分离
endpoints:
web:
exposure:
include: '*'
base-path: /actuator
endpoint:
health:
show-details: always
prometheus:
enabled: true
metrics:
export:
prometheus:
enabled: true八、实用技巧与最佳实践
1. 配置属性绑定
使用 @ConfigurationProperties:
@Component
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {
private String name;
private boolean enabled;
@Min(1000)
@Max(65535)
private int port;
private List<String> allowedIps = new ArrayList<>();
private Map<String, String> features = new HashMap<>();
// getters and setters
}启用方式:
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}配置文件:
app:
name: my-application
enabled: true
port: 8080
allowed-ips:
- "192.168.1.1"
- "10.0.0.1"
features:
dark-mode: true
notifications: false提示:
@ConfigurationProperties比@Value更适合复杂配置,提供类型安全和验证功能。
2. 外部化配置最佳实践
配置优先级策略:
- 环境变量(生产环境首选)
- 命令行参数(临时调试用)
- 配置中心(如 Spring Cloud Config)
- 项目内配置文件(开发环境用)
敏感信息处理:
- 生产环境绝不使用明文密码
- 使用系统环境变量或配置中心
- 开发环境可使用加密配置
3. 配置验证
使用 JSR-303 验证:
@Component
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {
@NotBlank
private String name;
@Min(1000)
@Max(65535)
private int port;
@NotEmpty
private List<String> allowedIps;
// getters and setters
}自定义验证:
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
public @interface ValidAppConfig {
String message() default "Invalid app configuration";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CustomValidator implements ConstraintValidator<ValidAppConfig, AppProperties> {
@Override
public boolean isValid(AppProperties value, ConstraintValidatorContext context) {
// 自定义验证逻辑
return value.getPort() > 0 && value.getAllowedIps() != null;
}
}九、常见问题与解决方案
1. 配置不生效问题
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 环境变量不生效 | 环境变量命名不正确 | 使用大写和下划线,如 SPRING_DATASOURCE_URL |
| 配置文件未加载 | 文件名或位置错误 | 确保是 application-{profile}.yml 且在 src/main/resources |
| profile 未激活 | 未正确设置 active profile | 检查 spring.profiles.active 配置 |
| 配置被覆盖 | 多个配置源冲突 | 了解配置加载顺序,检查优先级更高的配置源 |
2. 中文乱码问题
解决方案:
统一设置文件编码为 UTF-8
server: tomcat: uri-encoding: UTF-8 spring: http: encoding: charset: UTF-8 enabled: true force: true设置 JVM 参数
java -Dfile.encoding=UTF-8 -jar app.jarIDEA 设置
- File → Settings → Editor → File Encodings
- 设置全局编码、项目编码和属性文件编码为 UTF-8
3. 端口冲突问题
解决方案:
修改配置文件
server: port: 8081 # 更改端口号启动时指定端口
java -jar app.jar --server.port=8081查找并终止占用端口的进程
# Linux/Mac lsof -i :8080 kill -9 <PID> # Windows netstat -ano | findstr :8080 taskkill /PID <PID> /F
十、实用技巧速查表
| 场景 | 推荐配置 | 注意事项 |
|---|---|---|
| 本地开发 | dev profile + devtools | 开启热部署,关闭安全 |
| 测试环境 | test profile + 内存数据库 | 使用H2,自动创建/删除表结构 |
| 生产环境 | prod profile + 安全配置 | 关闭敏感端点,开启监控 |
| 多环境配置 | application-{env}.yml | 使用spring.profiles.active激活 |
| 敏感信息 | 环境变量或配置中心 | 避免提交到代码仓库 |
| 日志管理 | Logback + 按天滚动 | 设置合理的保留天数 |
| 性能监控 | Actuator + Prometheus | 暴露必要端点,保护敏感信息 |
| 配置验证 | @Validated + JSR-303 | 确保配置正确性 |
