1、好处:采用树状结构,一目了然
2、使用注意:
原来以.分隔的key会变成树状结构,例如:server.port=8080变成:
server: port: 8080 在key后的冒号与值之间一定要有一个空格,如:port:空格8080如果把原有的application.properties删除,建议执行一下:maven -X clean install命令YAML格式不支持用注解@PropertySource导入配置2、使用 1、在YAML文件中添加配置数据(springboot配置项+自定义配置项) server: port: 8081 servlet: session: timeout: 30 tomcat: uri-encoding: UTF-8age: 19name: mazhongjiapersoninfo: name: mazhongjia age: 34 2、通过@Value注解单个引用配置项 //获取配置文件中的age @Value("${age}") private int age; //获取配置文件中的name @Value("${name}") private String name; @Test public void getAge() { System.out.println(age); } @Test public void getName() { System.out.println(name); }其中@Test注解是junit中注解,不是重点
运行测试用例后成功
3、通过@ConfigurationProperties注解搜集配置项通过@ConfigurationProperties(prefix = "xxx")注解,将YAML中以xxx为前缀的配置项搜集到注解修饰的类中:
1)定义配置项类方式一:不使用JavaConfig配置类时
package com.mzj.springboot.actionpai.common;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "personinfo")public class GetPersonInfoProperties { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}使用@Component注解将类纳入spring的IOC容器
使用@ConfigurationProperties注解声明收集YAML中哪些配置项,这里是以personinfo为前缀的配置项
方式二:使用JavaConfig配置类时
可以把@ConfigurationProperties注解直接定义在JavaConfig类中@Bean所注解的方法上,这时Bean实体类就不需要使用@Component和@ConfigurationProperties进行声明了,如下:
2)将配置项类在使用处进行注入并使用 @Autowired private GetPersonInfoProperties getPersonInfoProperties; @Test public void getPersonproperties() { System.out.println(getPersonInfoProperties.getName()+getPersonInfoProperties.getAge()); }运行上面测试用例,可以正确获取配置项
三、properties 1、说明 四、配置多环境