先创建一个peron类,然后需要注解configurationProperties(prefix ="person")然后需要加一个@component因为只有在springboot的容器才能提供容器提供的@configurationProperties@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; 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; } @Override public String toString() { return "Person [lastName=" + lastName + ", age=" + age + ", boss=" + boss + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists + ", dog=" + dog + "]"; } }
dog类
public class Dog { private String Name; private Integer age; public String getName() { return Name; } public void setName(String name) { Name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Dog [Name=" + Name + ", age=" + age + "]"; } }
写完后,ide会提示需要在pom.xml中导入组件处理器。
<!-- 配置文件的处理器 ,配置文件进行绑定就会有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies>
然后创建配置文件,有两种方式,一个时yml文件,另一个时properties
1,application.yml
person: last-name: zhangsan age: 24 boss: false birth: 2017/12/5 maps: {k1: v1,k2: v2} lists: [lisi, zhangsan] dog: Name: xiaohei age: 4
2.application.properties
中文字,在eclipse中自动转为unicode码
person.age=24 person.last-name=\u5F20\u4E09 person.birth=2000/1/1 person.boss=false person.maps.k1=value1 person.maps.k2=12 person.dog.name=\u5C0F\u9ED1 person.dog.age=2
在test中使用spring boot的单元测试
@RunWith(SpringRunner.class) @SpringBootTest class Helloworld01QuickApplicationTests { @Autowired Person person; @Test void contextLoads() { System.out.println(person); } }
运行,会看到得到配置文件中的数据
原文地址:https://www.cnblogs.com/hamish26/p/12171877.html
时间: 2024-10-02 22:01:54