SpringBoot 读取YML文件内容

本文深入探讨了Spring Boot中YAML配置文件的加载与使用技巧,包括ConfigurationProperties注解的用法、YAML文件的多文档特性及如何解决前缀配置下的属性加载问题。

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

J2Cache 一级缓存数据


https://blog.csdn.net/luckyrocks/article/details/79248016 

根据以上博客,学习到的文件 引入问题


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.csdn.net/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.csdn.net/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

转载于:https://www.cnblogs.com/JC-0527/p/9516735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值