1、这里有不同类型属性的赋值,包括普通属性,对象,list,map
首先创建一个Person类包含一个Dog类,所以再创建一个Dog类
package com.athome.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 1、@ConfigurationProperties(prefix = "person") 说明这个类的属性要从配置文件里取值,并且名字是person,默认从全局配置文件里取值
* 可以使用@PropertySource( value ="classpath:person.properties" )指定配置文件
* 2、@Component:只有组件容器才能使用@ConfigurationProperties的功能
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Date birth;
private Boolean boss;
private Dog dog;
private List<String> lists;
private Map<String,Object> maps;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", birth=" + birth +
", boss=" + boss +
", dog=" + dog +
", lists=" + lists +
", maps=" + maps +
'}';
}
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 Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
}
package com.athome.bean;
public class Dog {
private String name;
private Integer age;
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
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;
}
}
2、配置pom文件导入配置文件处理器,这样当在配置文件内配置属性的时候会有提示,只是注意,导入成功后需要重启一下项目
<!--配置文件处理器,绑定数据时有提示信息-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3、包括propertiest,yaml,两种方式
(1)properties文件按配置
#person配置
person.last-name=练习
person.age=24
person.birth=1995/06/10
person.boss=false
person.dog.name=大黑
person.dog.age=8
person.lists=list1,list2,list3
person.maps.key1=v1
person.maps.key2=v2
(1)yaml文件按配置
person:
last-name: 练习2
age: 18
birth: 1995/06/10
boss: false
dog:
name: 大黑2
age: 8
lists:
- content1
- content2
maps:
key1: v1
key2: v2
3、创建一个测试类可以测试一下,就成功了