外部化配置
轻松的绑定
有关宽松绑定的规则已经收紧。我们假设一个现有的acme.my-project.my-name属性:
-
所有前缀必须是 kebab格式(小写,连字符分隔)acme.myProject或acme.my_project无效 - 您必须acme.my-project在此处使用。
-
属性名称可以使用 kebab-case(my-name),camel-case(myName)或 snake-case(my_name)。
-
环境属性(来自操作系统环境变量)必须使用通常的大写下划线格式,下划线只能用于分隔键的各个部分ACME_MYPROJECT_MYNAME。
这种新的放松绑定具有以下几个优点:
-
只要键值是按照标准格式定义的,就无需担忧在 @ConditionalOnProperty: 中键值的结构,被支持的宽松的变量将会自动透明的工作。如果你正在使用 prefix 属性,你可以简单地通过使用 name 或者value 属性 放入全键值。
-
源于Environment 关注自动化,RelaxedPropertyResolver 将不再可用:env.getProperty("com.foo.my-bar") 将找到一个 com.foo.myBar 属性。
org.springframework.boot.bind 包将不再可用,现被 new relaxed binding infrastructure 替换。特别是,RelaxedDataBinder 相关的应用方式被替换为新的绑定API。
下面的列子实现一个 com.foo 为前缀的配置到一个 POJO。
MyProperties target = Binder.get(environment)
.bind("app.acme", MyProperties.class)
.orElse(null);
由于现在内置了轻松绑定,因此只要使用其中一种支持的格式,就可以请求任何属性而不必关心案例:
FlagType flagType = Binder.get(environment)
.bind("acme.app.my-flag", FlagType.class)
.orElse(FlagType.DEFAULT);
@ConfigurationProperties 校验
如果要打开校验,需要在@ConfigurationProperties 对象上添加注解@Validated。
Configuration location 配置位置
spring.config.location 配置的实现已经配置设定;基于提前添加一个位置到默认配置列表,现在它替换了 默认配置。
如果你是按照以前的方式进行处理,你应该使用spring.config.additional-location进行替换。
Configuration Property Sources
Spring Boot 2.0不是直接使用现有的PropertySource接口进行绑定,而是引入了一个新的ConfigurationPropertySource接口。 我们引入了一个新的接口,为我们提供了一个合理的地方来实施放松绑定规则,这些规则以前是活页夹的一部分接口的主要API非常简单:
ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name);
还有一个IterableConfigurationPropertySource变相的实现了Iterable 接口,以便您可以发现源包含的所有名称。
通过使用以下代码,可以将Spring Environment调整为ConfigurationPropertySources
sources = ConfigurationPropertySources.get(environment);
如果您需要它,我们还提供一个简单的MapConfigurationPropertySource实现。
实例:
// 原来的code:
RelaxedPropertyResolver propertyResolver =
new RelaxedPropertyResolver(environment, "spring.datasource");
propertyResolver.getSubProperties("....")
// 现在的code:
Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
Binder binder = new Binder(sources);
BindResult<Properties> bindResult = binder.bind("spring.datasource", Properties.class);
Properties properties= bindResult.get();
网友评论