升级Spring Boot 2.x后RelaxedPropert

2019-08-21  本文已影响0人  Lord丶轩莫言弃

外部化配置

轻松的绑定

有关宽松绑定的规则已经收紧。我们假设一个现有的acme.my-project.my-name属性:

这种新的放松绑定具有以下几个优点:

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();

本文转载自:https://www.ouzengqi.com/detail/J3SH1cFi.html

上一篇 下一篇

猜你喜欢

热点阅读