springboot 配置属性


sprinboot 配置属性

                                  

官网:Spring Boot Features(Externalized Configuration)

                                

                                       

******************

命令行参数

                       

命令格式

# 虚拟机参数
java -Dserver.port=8000 -jar demo.jar
java -jar -Dserver.port=8000 demo.jar
java -jar demo.jar -Dserver.port=8000

# 应用参数(在jar包后面,其余位置会报错)
java -jar demo.jar --server.port=8000

                                  

                                                      

******************

命令行 json文件

                                       

命令格式

# 虚拟机参数
java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jar

# 应用参数
java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}'


# 与application.yml等效
my:
  name: test

                       

                         

******************

属性文件

                                  

ConfigFileApplicationListener:springboot 2.4开始不推荐使用,2.6计划移除

@Deprecated
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
    private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/";
                                //配置文件的默认加载目录
                                //目录层级加载顺序:classpath:/、classpath:/config/、
                                //          file:./、file:./config/、file:./config/*/
                                //同一目录层级,先加载yml、再加载properties
                                //相同属性,先加载的被后加载的覆盖

    private static final String DEFAULT_NAMES = "application";
                                //属性文件名称默认为application,如:application.yml

    private static final Set<String> NO_SEARCH_NAMES = Collections.singleton((Object)null);
    private static final Bindable<String[]> STRING_ARRAY = Bindable.of(String[].class);
    private static final Bindable<List<String>> STRING_LIST = Bindable.listOf(String.class);
    private static final Set<String> LOAD_FILTERED_PROPERTY;
    public static final String ACTIVE_PROFILES_PROPERTY = "spring.profiles.active";
    public static final String INCLUDE_PROFILES_PROPERTY = "spring.profiles.include";

    public static final String CONFIG_NAME_PROPERTY = "spring.config.name";
                               //属性文件名称,默认为application

    public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location";
                               //属性文件加载位置,如果指定了,则不从默认目录加载
                               //Config file locations that replace the defaults

    public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
                               //属性文件额外加载位置(同时从默认目录加载配置文件)

    public static final int DEFAULT_ORDER = -2147483638;
    private final Log logger;
    private static final Resource[] EMPTY_RESOURCES;
    private static final Comparator<File> FILE_COMPARATOR;
    private String searchLocations;
    private String names;
    private int order;

    public ConfigFileApplicationListener() {
        this(new DeferredLog());
    }

    ConfigFileApplicationListener(Log logger) {
        this.order = -2147483638;
        this.logger = logger;
    }

                                  

注意事项

spring.config.name, spring.config.location, and spring.config.additional-location 
are used very early to determine which files have to be loaded. 
三个配置参数决定配置文件的加载,使用得很早

They must be defined as an environment property (typically an OS environment variable, 
a system property, or a command-line argument).
应将这三个参数设置为环境参数、或者在命令行中使用

                    

示例

java -jar myproject.jar --spring.config.name=myproject
# 设置配置文件名称为myproject,
# 应用程序加载配置文件(myproject.properties、myproject.yml)

java -jar myproject.jar --spring.config.location=\
    optional:classpath:/default.properties,\
    optional:classpath:/override.properties
# 文件加载位置:classpath:/default.properties、classpath:/override.properties
# optional:如果文件不存在,不会报错

java -jar myproject.jar --spring.config.location=\
    optional:classpath:/default.properties,\
    optional:classpath:/dir/
# 同时指定加载的配置文件、配置目录
# 指定配置目录需要以“/”结尾


java -jar myproject.jar --spring.config.additional-location=\
    optional:classpath:/additional.properties,\
    optional:file:./additional-dir/
# 先加载默认属性文件,后加载additional属性文件
# 同名属性,additional文件会覆盖

                                           

*******************

profile 配置文件

               

示例

/cfg
  application-live.properties
/ext
  application-live.properties
  application-prod.properties


# location 逗号间隔,配置文件加载顺序:
先加载cfg目录,再加载ext目录;同目录层层级先加载prod,再加载live
spring.config.location = classpath:/cfg/,classpath:/ext/
spring.profiles.active = prod,live

/cfg/application-live.properties
/ext/application-prod.properties
/ext/application-live.properties


# location 分号间隔,配置文件加载顺序:
配置文件加载不分先后,在同一层级(process /cfg and /ext at the same level)
spring.config.location = classpath:/cfg/;classpath:/ext/
spring.profiles.active = prod,live

/ext/application-prod.properties
/cfg/application-live.properties
/ext/application-live.properties

                                

*******************

import 配置文件

                        

示例

# 导入配置文件dev.properties
spring.config.import=optional:file:./dev.properties


# 同一文档中,application.properties中spring.config.import
# 导入的文件会覆盖application.properties的同名属性
# 并且与spring.config.import的位置无关


# application.properties文件如下,my.properties如有my.property,
# 都会覆盖application.properties中的my.property属性
spring.config.import=my.properties
my.property=value

my.property=value
spring.config.import=my.properties

                               

导入不带拓展名的文件:myconfig

# 将文件导入为properties
spring.config.import=file:/etc/config/myconfig[.properties]

# 将文件导入为yml
spring.config.import=file:/etc/config/myconfig[.yml]

                                                

导入云平台配置树:key为目录节点名、value为目录内容

# 配置树
etc/
  config/
    myapp/
      username
      password


spring:
  config:
    import: "optional:configtree:/etc/config/"

应用导入的配置属性
myapp.username=value(/etc/config/myapp/username 目录内容)
myapp.password=value2(/etc/config/myapp/password 目录内容)

                                            

导入云平台多配置树

etc/
  config/
    dbconfig/
      db/
        username
        password
    mqconfig/
      mq/
        username
        password


spring:
  config:
    import: "optional:configtree:/etc/config/*/"


应用导入的配置
db.username=value(/etc/config/dbconfig/db/username)
db.password=value2(/etc/config/dbconfig/db/password)

mq.username=value3(/etc/config/mqconfig/mq/username)
mq.password=value4(/etc/config/mqconfig/mq/password)

                              

*******************

属性引用

                      

示例

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

app.description的属性值为:MyApp is a Spring Boot application

                               

*******************

使用随机数

                  

示例

my:
  secret: "${random.value}"         #随机值(包含字符、数字)
  number: "${random.int}"           #随机整数(int)
  bignumber: "${random.long}"       #随机整数(long)
  uuid: "${random.uuid}"            #uuid数
  number-less-than-ten: "${random.int(10)}"         #小于等于10的随机整数
  number-in-range: "${random.int[1024,65536]}"      #1024、65536之间的随机整数

                          

*******************

多文档属性文件

                            

yml分隔符:---

properties分隔符:#---

                             

示例:application.yml

spring:
  application:
    name: MyApp

---

spring:
  config:
    activate:
      on-cloud-platform: kubernetes
  application:
    name: MyCloudApp

                           

示例:application.properties

spring.application.name=MyApp

#---

spring.config.activate.on-cloud-platform=kubernetes
spring.application.name=MyCloudApp

                       

注意事项

分隔符前面不能有空格
分隔符紧邻的上下行不能为注释

                      

*******************

属性文件激活

                 

相关配置

# 激活dev,prod属性
spring.profiles.active=dev,prod

# 满足指定条件下激活
spring.config.activate.on-profile=
spring.config.activate.on-cloud-platform=

说明:spring.profiles.active不能与spring.config.activate.on-*在同一文档中出现

                            

示例

myprop:
  always-set

---

spring:
  config:
    activate:
      on-cloud-platform: "kubernetes"
      on-profile: "prod | staging"
myotherprop: sometimes-set

                                

CloudPlatform:云平台

public enum CloudPlatform {
    NONE {
        public boolean isDetected(Environment environment) {
            return false;
        }
    },

    CLOUD_FOUNDRY {
        public boolean isDetected(Environment environment) {
            return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
        }
    },

    HEROKU {
        public boolean isDetected(Environment environment) {
            return environment.containsProperty("DYNO");
        }
    },

    SAP {
        public boolean isDetected(Environment environment) {
            return environment.containsProperty("HC_LANDSCAPE");
        }
    },

    KUBERNETES {
        private static final String KUBERNETES_SERVICE_HOST = "KUBERNETES_SERVICE_HOST";
        private static final String KUBERNETES_SERVICE_PORT = "KUBERNETES_SERVICE_PORT";
        private static final String SERVICE_HOST_SUFFIX = "_SERVICE_HOST";
        private static final String SERVICE_PORT_SUFFIX = "_SERVICE_PORT";

        public boolean isDetected(Environment environment) {
            return environment instanceof ConfigurableEnvironment ? this.isAutoDetected((ConfigurableEnvironment)environment) : false;
        }

        private boolean isAutoDetected(ConfigurableEnvironment environment) {
            PropertySource<?> environmentPropertySource = environment.getPropertySources().get("systemEnvironment");
            if (environmentPropertySource != null) {
                if (environmentPropertySource.containsProperty("KUBERNETES_SERVICE_HOST") && environmentPropertySource.containsProperty("KUBERNETES_SERVICE_PORT")) {
                    return true;
                }

                if (environmentPropertySource instanceof EnumerablePropertySource) {
                    return this.isAutoDetected((EnumerablePropertySource)environmentPropertySource);
                }
            }

            return false;
        }

        private boolean isAutoDetected(EnumerablePropertySource<?> environmentPropertySource) {
            String[] var2 = environmentPropertySource.getPropertyNames();
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                String propertyName = var2[var4];
                if (propertyName.endsWith("_SERVICE_HOST")) {
                    String serviceName = propertyName.substring(0, propertyName.length() - "_SERVICE_HOST".length());
                    if (environmentPropertySource.getProperty(serviceName + "_SERVICE_PORT") != null) {
                        return true;
                    }
                }
            }

            return false;
        }
    },

    AZURE_APP_SERVICE {
        private static final String WEBSITE_SITE_NAME = "WEBSITE_SITE_NAME";
        private static final String WEBSITES_ENABLE_APP_SERVICE_STORAGE = "WEBSITES_ENABLE_APP_SERVICE_STORAGE";

        public boolean isDetected(Environment environment) {
            return environment.containsProperty("WEBSITE_SITE_NAME") && environment.containsProperty("WEBSITES_ENABLE_APP_SERVICE_STORAGE");
        }
    };

    private static final String PROPERTY_NAME = "spring.main.cloud-platform";

    private CloudPlatform() {
    }

    public boolean isActive(Environment environment) {
        String platformProperty = environment.getProperty("spring.main.cloud-platform");
        return this.isEnforced(platformProperty) || platformProperty == null && this.isDetected(environment);
    }

    public boolean isEnforced(Environment environment) {
        return this.isEnforced(environment.getProperty("spring.main.cloud-platform"));
    }

    public boolean isEnforced(Binder binder) {
        return this.isEnforced((String)binder.bind("spring.main.cloud-platform", String.class).orElse((Object)null));
    }

    private boolean isEnforced(String platform) {
        return this.name().equalsIgnoreCase(platform);
    }

    public abstract boolean isDetected(Environment environment);

    public boolean isUsingForwardHeaders() {
        return true;
    }

    public static CloudPlatform getActive(Environment environment) {
        if (environment != null) {
            CloudPlatform[] var1 = values();
            int var2 = var1.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                CloudPlatform cloudPlatform = var1[var3];
                if (cloudPlatform.isActive(environment)) {
                    return cloudPlatform;
                }
            }
        }

        return null;
    }
}

                           

                                   

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/120233243