springboot 加载自定义yml文件

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> 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

 

你可能感兴趣的:(Java)