- yml文件中定义对应的属性
student:
id: 1
name: "zhangsan"
email: 'zhangsan@qq.com'
age: 22
- 在实体类上,使用
@ConfiguretionProperties
注解并指定yml中某一个属性(此时会有提示,需要导入一个依赖包)
@Component
@ConfigurationProperties(prefix="student")
public class Student {
private int id;
private String name;
private String email;
private int age;
- 加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 创建对象,使用自动注入方式(@Autowired)
@SpringBootTest
class SpringbootCh01ApplicationTests {
@Autowired
Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
- 至此就可以看到student的值了.