Skip to content

Spring Boot配置方式

一、配置文件型

Spring Boot内置两种标准配置文件,存放于resources目录,统一管理端口、数据源、日志等参数。

  1. properties格式

    • 文件名:application.properties
    • 语法:key=value,层级用 . 分隔,无缩进要求
    application.properties
    1
    2
    3
    4
    5
    6
    7
    server.port=8080
    server.servlet.context-path=/api
    
    # 数据源
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=123456
    
  2. yml/yaml格式

    • 文件名:application.yml
    • 语法:key: value缩进表示层级,键值间必须加空格,缩进用空格
    application.yml
    server:
      port: 8080
      servlet:
        context-path: /api
    
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test
        username: root
        password: 123456
    
  3. 多环境配置

    • 公共文件:application.yml
    • 环境文件:application-dev.yml/test/prod.yml
    application.yml
    1
    2
    3
    4
    # 激活环境:dev
    spring:
      profiles:
        active: dev
    
  4. 配置文件优先级

外部 > 内部

jar 同级/config/ > jar 同级/ > classpath:/config/ > classpath:/


二、代码注解型

  1. @Value单个配置注入

    Value 单个配置注入
    @Value("${server.port}")
    private Integer port;
    
  2. @ConfigurationProperties 批量绑定配置

    ConfigurationProperties 批量绑定配置
    1
    2
    3
    4
    5
    6
    @Component@ConfigurationProperties(prefix = "app")
    public class AppConfig {
        private String name;
        private String version;
        // getter/setter
    }
    
  3. @Configuration + @Bean 组件配置

    Configuration + @Bean 组件配置
    1
    2
    3
    4
    5
    6
    7
    @Configuration
    public class BeanConfig {
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    

三、外部运行时

  1. 命令行参数(最高优先级)

    命令行参数
    java -jar app.jar --server.port=8081
    
  2. JVM 系统参数

    JVM 系统参数
    java -Dserver.port=8082 -jar app.jar
    
  3. 操作系统环境变量

    操作系统环境变量
    SERVER_PORT=8083
    SPRING_DATASOURCE_USERNAME=root
    

四、扩展方式

  1. @PropertySource 加载自定义配置文件;用于加载非默认名称的配置文件

    PropertySource 加载自定义配置文件
    1
    2
    3
    4
    @Configuration
    @PropertySource(value = "classpath:custom.properties", encoding = "UTF-8")
    public class CustomConfig {
    }
    
  2. 配置中心(生产环境)

Nacos、Apollo、Spring Cloud Config,支持统一管理、动态刷新配置。


配置优先级(从高到低)

命令行参数 > JVM 参数 > 环境变量 > 外置配置文件 > 内部配置文件 > 扩展配置 > 代码注解