springboot2中@ConfigurationProperties装载yml文件的时候调取出现值为null的解决办法

springboot2中@ConfigurationProperties装载yml文件的时候调取出现值为null的解决办法

@PropertySource只对properties文件可以进行加载,但对于yml或者yaml不能支持。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class YamlConfigFactory extends DefaultPropertySourceFactory {

@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = name != null ? name : resource.getResource().getFilename();
if (!resource.getResource().exists()) {
return new PropertiesPropertySource(sourceName, new Properties());
} else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
Properties propertiesFromYaml = loadYml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}

private Properties loadYml(EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}

然后再指定工厂类就可以读取

1
2
3
4
5
6
7
8
9
10
// 将类定义为一个bean的注解,比如 @Component,@Service,@Controller,@Repository
// 或者 @Configuration
@Configuration
// 表示使用配置文件中前缀为user1的属性的值初始化该bean定义产生的的bean实例的同名属性
// 在使用时这个定义产生的bean时,其属性name会是Tom
@PropertySource(value = "classpath:application-oss.yml",factory = YamlConfigFactory.class)
@ConfigurationProperties(prefix ="oss.upload")
@Validated
@Data
public class CloudStorageConfig implements Serializable {
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

扫一扫,分享到微信

微信分享二维码

请我喝杯咖啡吧~

支付宝
微信