首先确保依赖已被添加:
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor
implementation 'org.springframework.boot:spring-boot-configuration-processor:2.2.6.RELEASE'
定义自定义配置文件:
myyaml :
str : 字符串可以不加引号
specialStr : "双引号输出\n特殊字符"
specialStr2 : '单引号可转义\n特殊字符'
flag : false
num : 123
Dnum : 3.14159
list :
- one
- two
- two
set : [ 1 , 2 , 2 , 3 ]
map : { k1 : v1, k2 : v2}
positions :
- name : zhangsan
salary : 15000.00
- name : lisi
salary : 18888.88
编写对应该配置文件的配置类:
@Configuration
@ConfigurationProperties ( prefix = "myyaml" )
@Data
public class ConfigYML {
private String str;
private String specialStr;
private String specialStr2;
private Boolean flag;
private Integer num;
private Double dNum;
private List< Object> list;
private Set< Object> set;
private Map< String, Object> map;
private List< Person> positions;
}
加载并装配YML格式自定义配置文件(本测试文件存储在config目录下的myconfig目录下),该方法可放在启动类中:
@Bean
public static PropertySourcesPlaceholderConfigurer properties ( ) throws FileNotFoundException{
try {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer ( ) ;
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean ( ) ;
yaml. setResources ( new ClassPathResource ( "/myconfig/ymltest.yml" ) ) ;
configurer. setProperties ( Objects. requireNonNull ( yaml. getObject ( ) ) ) ;
return configurer;
} catch ( IllegalStateException e) {
Throwable cause = e. getCause ( ) ;
if ( cause instanceof FileNotFoundException ) {
throw ( FileNotFoundException) e. getCause ( ) ;
}
throw e;
}
}
测试可用