在springboot中可以只用yml或这properties类型的配置文件;通过框架自动读取配置信息如下:
一.读取yml:
1.通过@Value读取:
yml配置文件:
info1:
name: info1\n11
age: 1
city: beijing
#数组
pets:
- cat
- dog
- pig
pets2: [cat,dog,pig]
#map
friends:
lastName: zhangsan
age: 20
friends2: {lastName: zhangsan,age: 18}
@Value("${info1.city}")
private String city1;
(1)该方式只能读取基本类型信息,无法转换为对象;
(2)如果多个yml,需要将其他yml通过spring.profiles.active导入,否则无法读取(多配置文件存在相同key以后导入的生效)
2.通过实体读取(两种方式):
(1)直接声明为bean
@ConfigurationProperties(prefix = "info1")
@Data
@Component
public class Info1 {
private String name;
private Integer age;
private String city;
}
(2)通过配置集中导入
@ConfigurationProperties(prefix = "info1")
@Data
public class Info1 {
private String name;
private Integer age;
private String city;
}
@Configuration
@EnableConfigurationProperties({Info1.class})
public class InfoConfig {
}
该方式也是一样存在多个yml需要导入到主yml中;
二.properties方式的配置文件:
1.@Value:
(1)该方式跟上面一样.不过可以读取全部properties的配置的key(具有相同key以配置文件名称升序第一个为主,自己测的)
2.实体读取:
@ConfigurationProperties(prefix = "info1")
@PropertySource(value = {"classpath:application3.properties", "classpath:application2.properties"}, encoding = "utf-8")
@Data
@Component
public class Info1 {
private String name;
private Integer age;
private String city;
}
(1)必须指定配置文件路径,可以导入多个.不可使用通配符;
(2)多个配置文件存在相同key,以后面的配置文件为主;