SpringBoot 绑定配置文件测试输出值为空

tech2022-10-01  67

添加配置文件处理器依赖

<!-- 配置文件处理器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>

Person 类

package com.kwok.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; /** * 将配置文件中的每一个属性的值映射到该组件中 * @ConfigurationProperties * * @Component 只有这个组件是容器中的组件,才能使用容器提供的 Configuration 功能 */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; @Override public String toString() { return "Person{" + "lastName='" + lastName + '\'' + ", age=" + age + ", boss=" + boss + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists + ", dog=" + dog + '}'; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public boolean isBoss() { return boss; } public void setBoss(boolean boss) { this.boss = boss; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Map<String, Object> getMaps() { return maps; } public void setMaps(Map<String, Object> maps) { this.maps = maps; } public List<Object> getLists() { return lists; } public void setLists(List<Object> lists) { this.lists = lists; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } }

yaml 配置文件

server: port: 8081 person: lastName: zhangsan age: 32 boss: false birth: 1990/12/12 maps: {k1: v1,k2: v2} lists: - lisi - zhaoyun dog: name: bob age: 2

测试类

package com.kwok.springboot; import com.kwok.springboot.bean.Person; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * SpringBoot 单元测试 */ @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootHelloworldQuickApplicationTests { @Autowired Person person1; @Test public void contextLoads() { System.out.println(person1); } }

起初由于Person类没有添加Setting、Getting方法,输出的Person元组值为null,一直没找到原因,添加后成功输出:

左侧标志可以看出,set函数被用在了Spring Boot 配置函数中

最新回复(0)