使用yaml给实体类赋值(推荐)
创建一个实体类人类,然后写入属性字段,并且让为了让application.yaml文件可以读取到必须加入注解进行绑定
@ConfigurationProperties(prefix = “person”)这样yaml文件就可以找到配置类了
package com.xxr.dao;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private String sex;
private int age;
private Map<String,Object> map;
public Person() {
}
public Person(String name, String sex, int age, Map<String, Object> map) {
this.name = name;
this.sex = sex;
this.age = age;
this.map = map;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", map=" + map +
'}';
}
}
然后再application.yaml文件中编写配置类赋值
Person:
Person:
name: 辛星儒
age: 3
sex: 男
map: {v1: v1,v2: v2}
这样就可以给实体类赋值了。
在SpringBoot测试类中测试
package com.xxr;
import com.xxr.dao.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
这里说一个可以加载指定的配置文件的注解
@PropertySource(" ")这个样可以加载指定的配置文件。
版权声明:本文为XINGXINGR原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。