springboot 加载自定义yml文件

本文探讨了SpringBoot加载自定义yml文件的问题,包括ConfigurationProperties注解不再支持locations属性,PropertySource不支持yml加载,以及如何通过YamlPropertiesFactoryBean、YamlMapFactoryBean和PropertySourcePlaceholderConfigurer来加载yml。遇到yml中'---'分隔导致的属性获取问题,提出了两种解决方案:分开到不同文件或调整属性位置。同时提供了相关参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.  ConfigurationProperties注解的locations属性在1.5.X以后没有了,不能指定locations来加载yml文件

 

2. PropertySource注解不支持yml文件加载,详细见官方文档: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-yaml-shortcomings

 

3. Spring Framework有两个类加载YAML文件,YamlPropertiesFactoryBean和YamlMapFactoryBean

 

4. 可以通过PropertySourcePlaceholderConfigurer来加载yml文件,暴露yml文件到spring environment

 

// 加载YML格式自定义配置文件
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		yaml.setResources(new FileSystemResource("config.yml"));//File引入
//		yaml.setResources(new ClassPathResource("youryml.yml"));//class引入
		configurer.setProperties(yaml.getObject());
		return configurer;
	}

5. 可以直接通过@Value引入属性值注入Bean

 

@Component
@ConfigurationProperties(prefix = "prefix")
public class ConfigYML1 {
        // 以下属性可以直接获取
        private String name;
        private List<Map<String, String>> list = new ArrayList<>();

	@Value("${your.username}")
	private String username;
	
}

6. config.yml

 

prefix:
  name:
  list:
    - name: tech
      key: 123
      source: beijing
    - name: skill
      key: 987
      source: shanghai
---
your:
  username: test
---
list2:
  name: qwer
  url: http://blog.youkuaiyun.com/luckyrocks

7. Question:

 

在yml文件中,‘---’表示分隔符,表示多个yml,当Component在ConfigurationProperties注解的属性中prefix设置值后,list2无法直接加载为map,即如果你声明一个list2的map是没有值的,只能通过list2.name以字符串的形式获取到


8. Solutions:

 

 

yml文件以‘---’分隔的属性无法在写有前缀的情况下获取

a. 写到另外一个yml文件中,重新加载

b. 将list2后面的属性放到'prefix'前缀的后面,也可以获取

始终找不到满意的解决方法,你是怎么解决的?请告诉我

 

 

 

参考资料:

1. http://blog.youkuaiyun.com/tyrant_800/article/details/78780312

2. http://m.mamicode.com/info-detail-2006405.html

3. https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-yaml-shortcomings

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值