在网上找了很多种读取自定义yml文件与属性的东西,大部分都要定义实体类字段与配置文件中属性对应,新加属性或编辑自定义属性名会很麻烦,下面的方法只需要使用注解@value即可
1.首先写配置文件,用来读取yml文件 2.
1 package com.gd.ctripbusiness.config; 2 3 import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; 4 import org.springframework.core.env.PropertiesPropertySource; 5 import org.springframework.core.env.PropertySource; 6 import org.springframework.core.io.support.EncodedResource; 7 import org.springframework.core.io.support.PropertySourceFactory; 8 9 import java.io.FileNotFoundException; 10 import java.io.IOException; 11 import java.util.Properties; 12 13 14 public class YamlPropertySourceFactory implements PropertySourceFactory { 15 16 @Override 17 public PropertySource< ? > createPropertySource(String name, EncodedResource resource) throws IOException { 18 Properties propertiesFromYaml = loadYamlIntoProperties(resource); 19 String sourceName = name != null ? name : resource.getResource().getFilename(); 20 return new PropertiesPropertySource(sourceName, propertiesFromYaml); 21 } 22 23 private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException { 24 try { 25 YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); 26 factory.setResources(resource.getResource()); 27 factory.afterPropertiesSet(); 28 return factory.getObject(); 29 } catch (IllegalStateException e) { 30 Throwable cause = e.getCause(); 31 if (cause instanceof FileNotFoundException) { 32 throw (FileNotFoundException) e.getCause(); 33 } 34 throw e; 35 } 36 } 37 38 39 }
2.启动类加上自定义的的yml文件
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:xxx.yml")
3.在使用的时候用@value注解即可
@Value("${ccbb.des.a}") public String as1;
参考文章: https://blog.csdn.net/zxl8899/article/details/106382719