延伸:以后除了可以为实体类注入属性,还可以为配置类注入相关的配置信息
1.编写实体类
@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 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;
}
}
@Component
表示将当前类的创建工作交给Spring容器管理
@ConfigurationProperties(prefix = “person”)
用于表示该类需要读取的配置信息,prefix用于指示读取哪一个配置信息
Person类依赖了一个Dog类,如下:
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.编写yml文件
@ConfigurationProperties(prefix = “person”)
Person类的这个注解就会去找yml中对应的配置信息
person:
lastName: zhangsan
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: v2}
lists:
- lisi
- zhaoliu
- wangwu
dog:
name: 小狗
age: 2
3.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootQuickStartApplicationTests {
@Autowired
Person person;
@Test
public void demo1() {
System.out.println(person);
}
}
4.结果
注意:有可能中文在这个地方打印会出现乱码,原因是yml的编码和java文件的编码不一样导致,我们需要将其配成一致的编码,如都设置成utf-8。
5.可以不用@ConfigurationProperties(prefix = “person”)注解方式
使用@Value的方式注入属性值
@Value注解等价于:
以三个属性字段为例
我们既可以从配置文件取值,也可以通过字面量直接赋值,当属性值少的时候这种方式特别方便。
@Value("${person.lastName}")
private String lastName;
@Value("${person.age}")
private Integer age;
@Value("true")
private Boolean boss;
效果如下,由于只注入了三个属性,其余属性则为空
6.@ConfigurationProperties(prefix = “person”)
默认是从主配置文件中读取相关信息,我们可以使用
@PropertySource(value = {“配置文件的路径”})
来指定需要读取的配置文件
6.1写一个dog.properties配置Dog类的相关配置信息
dog.name=puppy
dog.age=24
6.2为Dog类注入属性
@PropertySource(value = {"classpath:dog.properties"})
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
private String name;
private Integer age;
6.3效果
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。