4-1说了yml文件置入JavaBean,properties文件也是一样的。
配置都一样,就是properties是这样写:
#private String lastName; #private Integer age; #private Boolean boss; #private Date birth; #private Map<String,Object> maps; #private List<Object> lists; #private Dog dog; #============================================================= #person.lastName 相当于 person.last-name person.last-name=BiHu person.age=18 person.boss=false person.birth=2025/10/10 person.maps.k1=value1 person.maps.k2=value2 person.lists=v1,v2,v3,v4 person.dog.name=小勾勾 person.dog.age=2
然后其他都一样的 即:
package com.bihu.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; //无论是properties 还是 yml 文件绑定映射 JavaBean 都是下面两个注解原理而且要导入对应gav,原理也说明白了 @Component @ConfigurationProperties(prefix = "person") public class JavaBean { 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 getBoss() { 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; } }JavaBean.java
我们在用Test 测试一下:
package com.bihu; import com.bihu.Bean.JavaBean; 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; @RunWith(SpringRunner.class) //有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效, @SpringBootTest public class ApplicationTests { //这里测试JavaBean @Autowired JavaBean Person; @Test public void contextLoads() { System.out.println(Person); } }ApplicationTests.java
发现小勾勾中文乱码 ,因为IDEA默认是UTF-8,我们在IDEA设置 查找 file Encodings ,编码换为UTF-8 右边是否转换ASCLL码 打钩即可
运行结果:
Person{lastName='BiHu', age=18, boss=false, birth=Fri Oct 10 00:00:00 CST 2025, maps={k1=value1, k2=value2}, lists=[v1, v2, v3, v4], dog=Dog{name='小勾勾', age=2}}
其实挺简单的