一 通过@ConfigurationProperties获取值(默认从全局配置文件中取值)
1.创建Bean
@ConfigurationProperties----告诉SpringBoot将本类中的属性与配置文件中相关配置(prefix=“xxx”)进行绑定
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Date birthday;
private Boolean boy;
private List<Object> list;
private Map<String,Object> maps;
private Animal animal;
...
get/set方法
...
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", boy=" + boy +
", list=" + list +
", maps=" + maps +
", animal=" + animal +
'}';
}
package com.mine.bean;
public class Animal {
private String name;
private Integer 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;
}
@Override
public String toString() {
return "Animal{" +
"name=" + name +
", age=" + age +
'}';
}
}
2 导入配置文件处理器、测试启动器
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3
application.yml
person:
name: LiDa
age: 20
birthday: 1995/02/23
boy: true
list:
- lier
- lisan
maps: {k1: str,k2: 12}
animal:
name: 大狗
age: 4
application.properties
#配置Person属性值
person.name=李大
person.age=20
person.birthday=1995/02/21
person.boy=true
person.list=a,b,c
person.maps.k1=value1
person.maps.k2=12
person.animal.name=大狗
person.animal.age=3
4 SpringBoot单元测试
//SpringBoot可以在运行期间很方便的类似编码一样进行自动注入容器等功能
@RunWith(SpringRunner.class) //使用Spring的驱动器运行
@SpringBootTest
public class ReadPropertiesTest {
@Autowired
private Person person;
@Test
public void propertiesTest()
{
System.out.println(person);
//Person{name='LiDa', age=20, birthday=Thu Feb 23 00:00:00 CST 1995, boy=true, list=[lier, lisan], maps={k1=str, k2=12}, animal=Animal{name=大狗, age=4}}
}
}
二 通过@value获取配置文件中的值
@Component
//@ConfigurationProperties(prefix = "person")
public class Person {
@Value("${person.name}")
private String name;
@Value("${person.age}") //或者使用SPEL直接赋值---#{12*2}
private Integer age;
private Date birthday;
private Boolean boy;
private List<Object> list;
private Map<String,Object> maps;
private Animal animal;
三 @Value和@ConfigurationProperties获取值比较
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
SPEL | 不支持 | 支持 |
复杂数据类型封装 | 支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
松散绑定 | 支持 | 不支持 |
取值 | 全局配置文件(application.properties/yml) | 全局配置文件 |
当只需要获取配置文件中某个值时,使用@Value
当对JavaBean的属性与配置文件进行映射,使用@ConfigurationProperties