Spring Boot配置详解

1. 配置文件概述

Spring Boot支持多种配置方式,提供了灵活的配置管理机制。配置文件是Spring Boot应用的核心组成部分,用于管理应用的各种参数和设置。

1.1 配置文件类型

Spring Boot支持以下配置文件格式:

  • Properties文件application.properties
  • YAML文件application.ymlapplication.yaml
  • JSON文件application.json
  • 环境变量
  • 命令行参数

1.2 配置文件优先级

Spring Boot按以下顺序加载配置(后面的会覆盖前面的):

  1. 命令行参数
  2. 系统环境变量
  3. JNDI属性
  4. 系统属性
  5. 配置文件(按优先级顺序)

2. Properties配置

2.1 基本语法

# 服务器配置
server.port=8080
server.servlet.context-path=/api
server.servlet.session.timeout=30m

# 数据库配置
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.root=INFO
logging.level.com.example.demo=DEBUG
logging.file.name=logs/application.log

2.2 多环境配置

application-dev.properties

# 开发环境配置
server.port=8080
spring.datasource.url=jdbc:h2:mem:devdb
spring.jpa.hibernate.ddl-auto=create-drop
logging.level.com.example.demo=DEBUG

application-test.properties

# 测试环境配置
server.port=8081
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=create
logging.level.com.example.demo=INFO

application-prod.properties

# 生产环境配置
server.port=8080
spring.datasource.url=jdbc:mysql://prod-server:3306/proddb
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
logging.level.root=WARN

3. YAML配置

3.1 基本语法

server:
  port: 8080
  servlet:
    context-path: /api
    session:
      timeout: 30m

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:
    root: INFO
    com.example.demo: DEBUG
  file:
    name: logs/application.log

3.2 多环境YAML配置

application.yml

spring:
  profiles:
    active: dev

---
spring:
  profiles: dev
server:
  port: 8080
logging:
  level:
    com.example.demo: DEBUG

---
spring:
  profiles: test
server:
  port: 8081
logging:
  level:
    com.example.demo: INFO

---
spring:
  profiles: prod
server:
  port: 8080
logging:
  level:
    root: WARN

4. 配置属性绑定

4.1 @ConfigurationProperties

创建配置属性类:

package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    
    private String name;
    private String version;
    private Database database;
    private List<String> features;
    private Map<String, String> settings;
    
    // 嵌套配置类
    public static class Database {
        private String host;
        private int port;
        private String username;
        private String password;
        
        // getter和setter方法
        public String getHost() { return host; }
        public void setHost(String host) { this.host = host; }
        public int getPort() { return port; }
        public void setPort(int port) { this.port = port; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    // 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 Database getDatabase() { return database; }
    public void setDatabase(Database database) { this.database = database; }
    public List<String> getFeatures() { return features; }
    public void setFeatures(List<String> features) { this.features = features; }
    public Map<String, String> getSettings() { return settings; }
    public void setSettings(Map<String, String> settings) { this.settings = settings; }
}

对应的配置文件:

app:
  name: "My Application"
  version: "1.0.0"
  database:
    host: "localhost"
    port: 3306
    username: "root"
    password: "123456"
  features:
    - "user-management"
    - "file-upload"
    - "email-notification"
  settings:
    max-file-size: "10MB"
    session-timeout: "30m"

4.2 使用配置属性

package com.example.demo.service;

import com.example.demo.config.AppProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AppService {
    
    @Autowired
    private AppProperties appProperties;
    
    public String getAppInfo() {
        return String.format("应用名称:%s,版本:%s", 
                           appProperties.getName(), 
                           appProperties.getVersion());
    }
    
    public String getDatabaseUrl() {
        AppProperties.Database db = appProperties.getDatabase();
        return String.format("jdbc:mysql://%s:%d", db.getHost(), db.getPort());
    }
}

5. 环境变量配置

5.1 环境变量设置

# Windows
set SPRING_PROFILES_ACTIVE=prod
set DB_USERNAME=root
set DB_PASSWORD=123456

# Linux/Mac
export SPRING_PROFILES_ACTIVE=prod
export DB_USERNAME=root
export DB_PASSWORD=123456

5.2 在配置文件中使用环境变量

# 使用环境变量
spring.datasource.username=${DB_USERNAME:defaultuser}
spring.datasource.password=${DB_PASSWORD:defaultpass}
spring.profiles.active=${SPRING_PROFILES_ACTIVE:dev}

6. 命令行参数配置

6.1 启动时传递参数

# 设置端口
java -jar app.jar --server.port=9090

# 设置配置文件
java -jar app.jar --spring.profiles.active=prod

# 设置数据库配置
java -jar app.jar --spring.datasource.url=jdbc:mysql://localhost:3306/mydb

6.2 程序化设置参数

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        // 添加命令行参数
        String[] newArgs = new String[args.length + 2];
        System.arraycopy(args, 0, newArgs, 0, args.length);
        newArgs[args.length] = "--server.port=8080";
        newArgs[args.length + 1] = "--spring.profiles.active=dev";
        
        SpringApplication.run(DemoApplication.class, newArgs);
    }
}

7. 配置验证

7.1 使用@Validated验证

package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Component
@ConfigurationProperties(prefix = "app")
@Validated
public class ValidatedAppProperties {
    
    @NotBlank(message = "应用名称不能为空")
    private String name;
    
    @NotBlank(message = "版本号不能为空")
    private String version;
    
    @Min(value = 1, message = "端口号必须大于0")
    @Max(value = 65535, message = "端口号不能超过65535")
    private int port;
    
    @NotNull(message = "数据库配置不能为空")
    private Database database;
    
    public static class Database {
        @NotBlank(message = "数据库主机不能为空")
        private String host;
        
        @Min(value = 1, message = "数据库端口必须大于0")
        @Max(value = 65535, message = "数据库端口不能超过65535")
        private int port;
        
        // getter和setter方法
        public String getHost() { return host; }
        public void setHost(String host) { this.host = host; }
        public int getPort() { return port; }
        public void setPort(int port) { this.port = port; }
    }
    
    // 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 int getPort() { return port; }
    public void setPort(int port) { this.port = port; }
    public Database getDatabase() { return database; }
    public void setDatabase(Database database) { this.database = database; }
}

7.2 自定义验证器

package com.example.demo.validator;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Email.EmailValidator.class)
public @interface Email {
    String message() default "邮箱格式不正确";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    
    class EmailValidator implements ConstraintValidator<Email, String> {
        private static final Pattern EMAIL_PATTERN = 
            Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
        
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null || value.isEmpty()) {
                return true; // 空值由@NotBlank处理
            }
            return EMAIL_PATTERN.matcher(value).matches();
        }
    }
}

8. 配置外部化

8.1 外部配置文件

# 指定外部配置文件位置
java -jar app.jar --spring.config.location=classpath:/application.yml,file:./config/

# 指定配置文件名称
java -jar app.jar --spring.config.name=myapp

8.2 配置中心集成

package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "app")
@RefreshScope // 支持配置热刷新
public class RefreshableAppProperties {
    private String name;
    private String version;
    
    // 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; }
}

9. 配置管理最佳实践

9.1 配置分层

config/
├── application.yml              # 基础配置
├── application-dev.yml          # 开发环境
├── application-test.yml        # 测试环境
├── application-prod.yml        # 生产环境
└── application-secret.yml      # 敏感配置(不提交到版本控制)

9.2 敏感信息处理

# 使用占位符
spring:
  datasource:
    username: ${DB_USERNAME:defaultuser}
    password: ${DB_PASSWORD:defaultpass}
    url: ${DB_URL:jdbc:h2:mem:testdb}

9.3 配置文档化

package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.Description;

@Component
@ConfigurationProperties(prefix = "app")
public class DocumentedAppProperties {
    
    @Description("应用名称")
    private String name;
    
    @Description("应用版本")
    private String version;
    
    @Description("服务器端口")
    private int port = 8080;
    
    // 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 int getPort() { return port; }
    public void setPort(int port) { this.port = port; }
}

10. 配置调试

10.1 配置信息端点

# 启用配置信息端点
management:
  endpoints:
    web:
      exposure:
        include: configprops,env
  endpoint:
    configprops:
      show-values: always

访问配置信息:

  • 所有配置:GET /actuator/env
  • 配置属性:GET /actuator/configprops

10.2 配置调试工具

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ConfigController {
    
    @Autowired
    private Environment environment;
    
    @GetMapping("/config")
    public Map<String, Object> getConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("activeProfiles", environment.getActiveProfiles());
        config.put("defaultProfiles", environment.getDefaultProfiles());
        config.put("serverPort", environment.getProperty("server.port"));
        config.put("databaseUrl", environment.getProperty("spring.datasource.url"));
        return config;
    }
}

11. 总结

Spring Boot的配置系统提供了强大而灵活的配置管理能力:

  1. 多种配置格式:支持Properties、YAML、JSON等格式
  2. 环境分离:支持多环境配置管理
  3. 属性绑定:使用@ConfigurationProperties进行类型安全的配置绑定
  4. 配置验证:支持JSR-303验证注解
  5. 外部化配置:支持外部配置文件和配置中心
  6. 配置调试:提供配置信息查看和调试工具

通过合理使用这些配置特性,可以构建出易于维护和部署的Spring Boot应用。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小凯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值