一、读取yml配置文件的值
单引号和双引号的区别:
- 单引号不会保存其功能;
- 双引号会保存功能。
name: "123\n123"
输出:
123
123
name: '123\n123'
输出:123\n123
二、读取properties配置文件的值
代码
配置文件
server.port=8080
person.name=张三
person.age=18
person.birth=2020/01/01
person.b=true
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=xiaogou
person.dog.age=10
person 类中的修改:
需要:
- 类前面加入 @Component
- 在每个变量上面加入:@Value(“${person.name}”),这要跟配置文件保持一致
package com.zy.springboot.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/***
*
* 读取配置文件中的数据,映射到此类的同名属性
* @ConfigurationProperties
* prefix = "person": 读取person节点的数据
* @Component:让spring容器管理此类
*
*@Value("${person.name}") 参数名字必须和配置文件中的一样,即可跳转
*/
@Component
//@ConfigurationProperties(prefix = "person")
public class Person {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@Value("${person.birth}")
private Date birth;
@Value("${person.b}")
private Boolean b;
private Map<String,String> maps;
private List<String> lists;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Boolean getB() {
return b;
}
public void setB(Boolean b) {
this.b = b;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
", b=" + b +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
}
三、解决乱码
在显示中文中,
解决中文乱码,一定要在代码之前就配置好这个环境:
展示