写入实体类

添加注解:
@Component
@ConfigurationProperties(prefix = “person”)
这个注解的依赖如下:
@ConfigurationProperties(prefix = “person”)
<!--读取配置文件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
写yml配置文件:
person:
name : houaid
age : 10
map : {a: 1,b: 2}
测试:
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果:读取成功

本文介绍了如何使用Spring Boot的@ConfigurationProperties注解从YML配置文件中读取属性。通过添加@ConfigurationProperties(prefix = person)注解到Person实体类,并在YML配置文件中定义person对象,成功实现了属性注入。在测试类中,通过@Autowired自动装配Person对象并打印,测试结果显示配置读取成功。

1298

被折叠的 条评论
为什么被折叠?



