1 书写javabean
注意:一定要在主类下的子包建立才行,这样才能自动扫描组件。
package com.itrucheng.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component //下面的注解依赖于这个注解,必须要将对象放在spring容器中才能使用
@ConfigurationProperties(prefix = "person") //书写这个是从yml文件中获取名为person的数据
public class Person {
private String name;
private Integer age;
private Boolean boss;
private Map<String, Object> maps;
private List<Object> list;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", boss=" + boss +
", maps=" + maps +
", list=" + list +
", dog=" + dog +
'}';
}
}
application.yml
person:
name: zhangsan
age: 18
boss: false
maps: {k1: v1, k2: v2}
list:
- lisi
- wangwu
dog:
name: wangcai
age: 2
2 导入配置处理器依赖
在pom.xml中导入依赖,能够在yml、properties自动提示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3 单元测试
在测试类中书写:
package com.itrucheng.springboot;
import com.itrucheng.springboot.bean.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired //从容器中获取该person
private Person person;
@Test
void contextLoads() {
System.out.println(person); //打印person
}
}
运行后得到控制台结果:
Person{name=‘zhangsan’, age=18, boss=false, maps={k1=v1, k2=v2}, list=[lisi, wangwu], dog=Dog{name=‘wangcai’, age=2}}