EnableConfigurationProperties 的基本使用

EnableConfigurationProperties 的基本使用

  • 官方解释
    Enable support for @ConfigurationProperties annotated beans. @ConfigurationProperties beans can be registered in the standard way (for example using @Bean methods) or, for convenience, can be specified directly on this annotation.
    启用对 @ConfigurationProperties 注释 bean 的支持。 @ConfigurationProperties beans 可以以标准方式注册(例如使用@Bean 方法),或者为了方便起见,可以直接在此注释上指定。

  • 注意 : 通常情况下,如果我们需要把 Properties 类标记成一个 Bean:
    1、在该类上添加 @Component 注解
    2、在 标注有 @Configuration 类上注册这个类

@ConfigurationProperties 使用

  • @ConfigurationProperties 可以把 resouce 下的 application.yml 或者 appication.properties 文件的资源注入到实体类上
@ConfigurationProperties(prefix = PersonProperties.PERFIX)
@ToString
@Data
public class PersonProperties {
    
    public static final String PERFIX = "person";
    
    private int age;

    private String name;

}
  • 注意 : 根据上面的编码就可以把 application.yml 上边的资源注入到实体类 PersonProperties 中,但是此时 PersonProperties 这个类还不是一个被 Spring 容器所管理的资源 (Bean)

@EnableConfigurationProperties

  • @EnableConfigurationProperties 可以通过自动配置技术导入相应的 Properties 资源类
@EnableConfigurationProperties(PersonProperties.class)
@RequiredArgsConstructor
public class PersonConfiguration implements ApplicationRunner {

    private final PersonProperties personProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(personProperties);
    }
}
  • 注意 : 此时需要注意 PersonConfiguration 还不是一个 配置类,如果想要成为一个配置类可以在类上添加 @Configuration 注解
posted @ 2023-05-25 23:48  ayiZzzz  阅读(745)  评论(0)    收藏  举报