springboot使用配置文件给对象属性赋值
第一种(优先):
1 @Component 2 @ConfigurationProperties(prefix = "person") 3 public class Person { 4 5 }
配置yaml文件:
1 person: 2 name: xianzaikaishi 3 age: ${random.int} 4 happy: true 5 birth: 2022/06/22 6 maps: {k1: v1, k2: v2} 7 hello: test 8 lists: 9 - code 10 - music 11 - girl 12 dog: 13 name: ${person.hello:hello}_小白 14 age: 11
需要导入依赖,否则会有个提示(提示也不会影响什么,就是看着别扭):
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-configuration-processor</artifactId> 4 <optional>true</optional> 5 </dependency>
第二种:
指定了配置文件
1 @Component 2 @PropertySource(value = "classpath:xianzaikaishi.yaml") 3 public class Person { 4 5 @Value("${name}") 6 private String name; 7 private Integer age; 8 }
配置yaml文件:
1 name: test

浙公网安备 33010602011771号