application.properties和application.yml配置文件, 分别从数组,List集合,Set集合,Map集合等比较这两种配置文件的语法用法。
1,创建springboot项目
2,pojo
@Getter
@Setter
@ToString
@Component
@ConfigurationProperties(prefix = "spring.myuser")
public class User {
private Integer uid;
private String username;
private Integer age;
private Date birth;
private String[] hobby;
private List<String> lists;
private Map<String,String> maps;
private Set<String> sets;
}
创建一个User类,@ConfigurationProperties(prefix = "spring.myuser")//该注解的作用是获取配置文件中对应属性值,给对应的对象注入,需要把User对象放到容器中@Component。prefix//属性是设置配置文件前缀。使用该注解会提示你导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3,application.properties配置文件设置值
server.port=8083
spring.myuser.uid=1
spring.myuser.username=zhangsan1
spring.myuser.age=10
spring.myuser.birth=1998/09/10
spring.myuser.hobby=唱,跳,rap,篮球
spring.myuser.lists=唱,跳,rap,篮球
spring.myuser.sets=唱,跳,rap,篮球
spring.myuser.maps.key1=a
spring.myuser.maps.key2=c
spring.myuser.maps.key3=b
4,测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests {
@Autowired
private User user;
@Test
public void contextLoads() {
System.out.println(user);
}
}
5,新建application.yml配置文件,因为在同一个目录下,application.properties的优先级比application.yml高,所以当文件共同存在时,如果内容相同,会优先使用优先级高的配置;不相同则会一起被使用,互补。application.yml配置文件中主要要注意:空格问题。
spring:
myuser:
id: 999
username: wangwu
age: 19
birth: 2000/09/03
hobby:
- chang
- tiao
- rap
lists:
- chang
- tiao
- rap
sets:
- chang
- tiao
- rap
maps:
-keya: a
-keyb: b
6,配置文件中可以使用${},获取容器中的值或者获取随机数值。
#生到10-100的随机int数
spring.myuser.age=${random.int[10,100]}
#生成一个int的随机数据
spring.myuser.maps.key1=${random.int}
#${random.value}生成一个随机数
spring.myuser.maps.key2=${random.value}
#生成一个long的随机数据
spring.myuser.maps.key3=${random.long}
7,@ConfigurationProperties(prefix = "spring.myuser"),可以与@Value("")替换,如下:
@Getter
@Setter
@ToString
@Component
//@ConfigurationProperties(prefix = "spring.myuser")
public class User {
@Value(value = "${spring.myuser.uid}")
private Integer uid;
@Value(value = "${spring.myuser.username}")
private String username;
@Value(value = "${spring.myuser.age}")
private Integer age;
@Value(value = "${spring.myuser.birth}")
private Date birth;
@Value(value = "${spring.myuser.hobby}")
private String[] hobby;
@Value(value = "${spring.myuser.lists}")
private List<String> lists;
@Value(value = "${spring.myuser.sets}")
private Set<String> sets;
// @Value(value = "${spring.myuser.maps}")//会抛出异常:Could not resolve placeholder 'spring.myuser.maps' in value "${spring.myuser.maps}"
private Map<String,String> maps;
}
@ConfigurationProperties() 和 @Valu("e")都可以获取属性注入,但是@Value("")不能获取Map类型属性。