spring-boot中使用ConfigurationProperties为bean赋值

881 阅读1分钟

1.pom中加依赖,为了绑定属性值:

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

2.设置需要的属性值

student:
  name: yml
  age: 10
  map: {key1:1,key1:2}
  list: [1,2]

3.绑定属性值

@Component
@Data
@ConfigurationProperties(prefix = "student")

一定要加上组件这个注解,@ConfigurationProperties默认是从application.yml中去取数据。

4.自定义配置文件

@Data
@Component
@PropertySource("teach.properties")
@ConfigurationProperties(prefix = "teach")
public class Teach {
    private String name;
}