Spring Boot 提供了灵活的配置方式和强大的自动配置机制,大大简化了 Spring 应用的配置工作。
配置文件类型
- application.properties - 属性文件格式
- application.yml - YAML 格式,支持层次结构
- 环境特定配置 - application-{profile}.properties/yml
常用配置示例
# 服务器配置
server.port=8080
server.servlet.context-path=/myapp
# 数据库配置
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
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# 日志配置
logging.level.com.example=DEBUG
logging.level.org.springframework.web=INFO
server:
port: 8080
servlet:
context-path: /myapp
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL8Dialect
logging:
level:
com.example: DEBUG
org.springframework.web: INFO
自定义配置属性
// 配置类
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private String version;
private List servers = new ArrayList<>();
// getter 和 setter 方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public List getServers() { return servers; }
public void setServers(List servers) { this.servers = servers; }
}
// 配置文件中添加
# application.properties
app.name=My Spring Boot App
app.version=1.0.0
app.servers[0]=server1.example.com
app.servers[1]=server2.example.com
Profile 配置
# application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb_dev
logging.level.com.example=DEBUG
# application-prod.properties
spring.datasource.url=jdbc:mysql://prod-server:3306/mydb_prod
logging.level.com.example=WARN
# 激活特定 profile
# 方式1:配置文件
spring.profiles.active=dev
# 方式2:命令行参数
java -jar app.jar --spring.profiles.active=prod
# 方式3:环境变量
export SPRING_PROFILES_ACTIVE=prod
自动配置原理
- @SpringBootApplication - 组合注解,包含 @EnableAutoConfiguration
- spring.factories - 自动配置的注册文件
- @Conditional - 条件注解,控制配置类的生效条件
- 自动配置报告 - 使用 debug=true 查看自动配置详情
查看自动配置
# 在 application.properties 中启用调试
debug=true
# 启动应用后,控制台会输出:
# Positive matches (生效的配置)
# Negative matches (未生效的配置)
# Exclusions (排除的配置)
# Unconditional classes (无条件配置)
提示: 这是一个重要的概念,需要特别注意理解和掌握。
注意: 这是一个常见的错误点,请避免犯同样的错误。
评论
请 登录 后发表评论