future.png
珠玑随笔

联系:

future.png

版权 © 2022 by Hsu

技术: Gatsby

样式: Bulma

许可: CC BY NC SA 4.0

Spring Boot 配置文件及环境变量

2022年01月06日

Hsu

1分钟

背景

Spring Boot 使用 application.properties 或者 application.yml 的格式进行配置.

环境变量使用 ${环境变量名:默认值} 的格式.

properties

spring.application.name=api-gateway
server.port=8000
server.servlet.context-path=/api

spring.profiles.active=${ENV_PROFILE:dev}

logging.level.root=${LOGGING_LEVEL_ROOT:info}

yaml

server:
  application:
    name: api-gateway
  servlet:
    context-path: /api
  port: 8000

spring:
  profiles:
    active: ${ENV_PROFILE:dev}

logging:
  level:
    root: ${ENV_LOGGING_LEVEL_ROOT:info}

读取

设置两个自定义的配置.

limits.min=0
limits.max=999

@Value

@RestController
public class ExchangeController {

  @Value("${limits.min}")
  private int min;

  @Value("${limits.max}")
  private int max;
}

Environment

@RestController
public class ExchangeController {

  @Autowired
  private Environment environment;

  @GetMapping("/limits")
  public void exchangeValue() {

    int min = environment.getProperty("limits.min");
    int max = environment.getProperty("limits.max");
  }
}

@Component @ConfigurationProperties

@Component
@ConfigurationProperties("limits")
@Getter
public class Config {

  private int min;
  private int max;
}
@RestController
public class LimitsController {

  @Autowired
  private Config config;

  @GetMapping("/limits")
  public void retrieveLimits() {

    System.out.println(config.getMin())
    System.out.println(config.getMax())
  }
}