1.编写javabean:
package com.example.springboot.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.Map; /** * @PROJECT_NAME:spring-boot-01-hello * @Data:2019/10/7 @ConfigurationProperties 告诉SpringBoot将配置文件中对应属性的值,映射到这个 组件类中,进行一一绑定 * prefix = "emp":配置文件中的前缀名,哪个前缀与下面的所有属性进行一一映射 * 2、@Component 必须将当前组件作为SpringBoot中的一个组件,才能使用容器提供的 */ @Component @ConfigurationProperties(prefix = "emp") public class Emp { private String lastName; private Integer age; private Double salary; private Boolean boss; private Date birthday; private Map map; private List list; private Forte forte; @Override public String toString() { return "Emp{" + "lastName='" + lastName + '\'' + ", age=" + age + ", salary=" + salary + ", boss=" + boss + ", birthday=" + birthday + ", map=" + map + ", forte=" + forte + '}'; } get and set..... }
2.yml文件
server: port: 8088 # emp配置数据 emp: lastName: Zane age: 28 salary: 2000 boss: True birthday: 2019/09/09 map: key1: value1 key2: value2 list: - one - two - three forte: name: java time: 8
通过@ConfigurationProperties(prefix = "emp")可以将yml文件与bean文件关联起来
注意:
1.emp上方出现如下提示
我们只需导入配置文件处理器即可
1 <!--导入配置文件处理器,在编写配置文件时就会提示 在pom.xml--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-configuration-processor</artifactId> 5 <optional>true</optional> 6 </dependency>