配置文件数据:
person:
name: linzhi
age: 18
读取配置文件数据:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @ConfigurationProperties:类中属性和yml配置文件中键值一一映射
* prefix = "person":声明配置文件中哪个键值进行一一映射
* @Component:把类添加到容器里
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"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;
}
}
单元测试:
@SpringBootTest
class Sbdemo01ApplicationTests {
//@Autowired:使用的时候要自动加载,不然值会为null
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
注意事项:
PS:读取的是yml配置文件,配置数据必须放在application.yml中,否则读不到
1、【映射读取类】的getter、setter方法要记得添加
2、【映射读取类】的注解要记得添加
(1)@Component //添加到容器中, @ConfigurationProperties(prefix = "person")注解的功能才能生效
(2) @ConfigurationProperties(prefix = "person") //声明类与配置文件的映射关系
3、使用【映射读取类】时需要添加 @Autowired 注解进行自动从容器中加载,不加的话读取到的数据为null
4、pom.xml添加以下配置文件处理器依赖,设置配置文件数据会有提示:
<!--配置文件处理器:配置文件与类进行绑定会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
提示: