首先建立一個簡單的實體類,我這里以學生為例,並加上@Component和@ConfigurationProperties(prefix ="student")注解,其中prefix ="student"對應yml文件中的student
package com.example.demomybatis.model; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Map; @Component//將此javaBean加入到spring容器中 @ConfigurationProperties(prefix ="student") public class Student { private String name; private Map<String,Object> location; public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Object> getLocation() { return location; } public void setLocation(Map<String, Object> location) { this.location = location; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", location=" + location + '}'; } }
然后在yml文件中對student屬性進行配置
student:
name: yyy
location: {province: 浙江}//map類型配置寫法
此外,要在pom.xml中加入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>