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>