首先建立一个简单的实体类,我这里以学生为例,并加上@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>