@springboot读取配置文件的两种方式

1. application.yaml文件格式

yml文件是以数据为中心,配置语法主要是注意空格,key: (空格) value

person:
  name: 张三
  age: 3
  birth: 2020/02/20
  books: ["水浒","三国","西游"]
  lists:
    - code
    - play
    - sleep
  maps: {k1: v2,k2: v2}
  dog:
    name: 旺财
    age: 3

dog:
  name: 小花
  age: 3

cat:
  name: 毛毛
  age: 3

在java中引入yml文件的手动配置
preson类中的属性要和yml文件中的属性完全一致,否则赋值失败
@ConfigurationProperties作用:将配置文件中的每一个属性的值,映射到这个组件中,告诉springboot将本类中的所有属性和配置文件中的关联属性相互绑定,参数(perfix = “student”)
注意:只有这个类组件是一个容器中的组件才可用@ConfigurationProperties(就是需要加上@Component注解)

import lombok.AllArgsConstructor;
	import lombok.Data;
	import lombok.NoArgsConstructor;
	import org.springframework.boot.context.properties.ConfigurationProperties;
	import org.springframework.stereotype.Component;
	
	import java.util.Date;
	import java.util.List;
	import java.util.Map;
	
	// lombok插件
	@Data  // getter setter
	@AllArgsConstructor // 有参构造方法
	@NoArgsConstructor  // 无参构造方法
	@Component  // 表示本类是一个组件
	/*
	*   在java中引入yml文件的手动配置
	    person类中的属性要和yml文件中的属性完全一致,否则赋值失败
	    @ConfigurationProperties作用:将配置文件中的每一个属性的值,映射到这个组件中,告诉springboot将本类中的所有属性和配置文件中的关联属性相互绑定,参数(perfix = “student”)
	    注意:只有这个类组件是一个容器中的组件才可用@ConfigurationProperties(就是需要加上@Component注解)
	* */
	@ConfigurationProperties(prefix = "person")
	public class Person {
	    private String name;
	    private Integer age;
	    private Date birth;
	    private List books;
	    private List lists;
	    private Map<String,Object> maps;
	    private Dog dog;
	}

@Test类
注意这个的@Autowired每一个都需要加上,否则自动注入失败

@Autowired
    Person person;
    @Autowired
    Dog dog;
    @Autowired
    Cat cat;

    @Test
    void contextLoads() {
        System.out.println(person);
        System.out.println(dog);
        System.out.println(cat);
    }

输出结果

Person(name=张三, age=3, birth=Thu Feb 20 00:00:00 CST 2020, books=[水浒, 三国, 西游], lists=[code, play, sleep], maps={k1=v2, k2=v2}, dog=Dog(name=旺财, age=3))
Dog(name=小, age=3)
Cat(name=毛, age=3)

2. application.properties文件格式

properties文件格式

name = zhangsan

注意:必须加上@Component注解
xxx.properties名字可以随意写,但是.properties只能是他
@Value可以采用SPEL表达是赋值

@Component
	@PropertiesSource(value = "classpath:xxx.properties")
	public class Person {
		@Value("${name}")
	    private String name;
	    private Integer age;
	    private Date birth;
	    private List books;
	    private List lists;
	    private Map<String,Object> maps;
	    private Dog dog;
	}

输出结果

Person(name=zhangsan, age=null, birth=null, books=null, lists=null, maps=null, dog=null)