利用Binder解析任意yaml或properties

1,703 阅读1分钟

问题

遇到一个需求,需要在非SpringBoot Context下,将任意一个yaml或properties绑定到配置类

思路

可以用专门解析yaml或properties的解析类去解析,但还要绑到配置类,暂时没有研究这种解法
转而考虑利用SpringBoot的Binder解析和绑定

  1. Binder提供一个静态方法get(Environment environment),实际上他用到了Environment里的PropertySources.
  2. 为了构造PropertySources,借用YamlPropertySourceLoaderPropertiesPropertySourceLoader加载yaml或properties.

代码

最终实现代码如下:
yaml

StandardEnvironment environment = new StandardEnvironment();
DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
Resource resource = defaultResourceLoader.getResource("file:/xxx/application.yaml");
// 加载yaml用YamlPropertySourceLoader
List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load("yaml", resource);
propertySourceList.forEach(propertySource -> environment.getPropertySources().addLast(propertySource));
DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class);

properties

StandardEnvironment environment = new StandardEnvironment();
DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
Resource resource = defaultResourceLoader.getResource("file:/xxx/application.properties");
// 加载properties用PropertiesPropertySourceLoader
List<PropertySource<?>> propertySourceList = new PropertiesPropertySourceLoader().load("properties", resource);
propertySourceList.forEach(propertySource -> environment.getPropertySources().addLast(propertySource));
DataSourceProperties dataSourceProperties = Binder.get(environment).bindOrCreate("spring.datasource", DataSourceProperties.class);