工作生活

SpringBoot_9 外部化配置

2019-07-06  本文已影响0人  o______o

返回目录

外部化配置


Spring Boot允许您外部化配置,以便您可以在不同的环境中使用相同的应用程序代码。您可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。

属性值可以通过@Value注解直接注入到你的Bean ,通过Spring的Environment抽象访问,或者通过@ConfigurationProperties绑定到结构化对象。

Spring Boot使用一种非常特殊的PropertySource顺序,旨在允许合理地覆盖值。按以下顺序考虑属性:

这里只列出常用的

  1. 命令行参数。
  2. 来自SPRING_APPLICATION_JSON(嵌入在环境变量或系统属性中的内联JSON)的属性。
  3. Java系统属性(System.getProperties())。
  4. OS环境变量。
  5. RandomValuePropertySource产生随机值函数的方法源random.*
  6. 打包jar之外或之内的应用程序属性(application.properties以及application.yml)。
  7. @PropertySource 你的@Configuration注解上的类的属性配置。
  8. 默认属性(由设置指定SpringApplication.setDefaultProperties)。

属性取值示例:


import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
@Component
public class MyBean {
    @Value("${name}")
    private String name;
    // ...
}

命令行设置属性


$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar
$ java -jar myapp.jar --spring.application.json='{"name":"test"}'

配置随机值


my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

服务器端口配置:server.port=80

application.properties可在位置


列表按优先级排序
(在列表中较高位置定义的属性将覆盖在较低位置中定义的属性)

如果您不喜欢application.properties配置文件名,可以通过指定spring.config.name环境属性切换到另一个文件名。

属性中的占位符


使用时,值application.properties将通过现有值进行过滤Environment ,因此您可以返回先前定义的值(例如,从“系统”属性)

app.name=MyApp
app.description=${app.name} is a Spring Boot application

YAML和properties互换


yml:

environments:
    dev:
        url: https://dev.example.com
        name: Developer Setup
    prod:
        url: https://another.example.com
        name: My Cool App
my:
servers:
    - dev.example.com
    - another.example.com

properties:

environments.dev.url=https://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=https://another.example.com
environments.prod.name=My Cool App
my.servers[0]=dev.example.com
my.servers[1]=another.example.com

使用@PropertySource注释无法加载YAML文件。因此,如果您需要以这种方式加载值,则需要使用属性文件。

其他方式


上一篇下一篇

猜你喜欢

热点阅读