信步漫谈之SpringBoot配置相关注释


目标

  • @EnableConfigurationProperties、@ConfigurationProperties、@Configuration 区别和用法

@ConfigurationProperties

  • 将我们项目中的 yaml 文件或者 properties 文件加载到 bean 对象进行使用

@EnableConfigurationProperties

  • @EnableConfigurationProperties 的作用是把 springboot 配置文件中的值与我们的 xxxProperties.java 的属性进行绑定,需要配合 @ConfigurationProperties 使用
  • @EnableConfigurationProperties 中引用的类一定要加 @ConfigurationProperties 这个注解,并且不需要再添加 @Component 注解,不然会导致被 @ConfigurationProperties 注解的类,在容器中实例化了 2 个 bean 对象
  • 容器注入的方法
  • @ConfigurationProperties 加 @Configuration 或 @Component
  • 通过 @EnableConfigurationProperties 实现

@Configuration

  • @Configuration 用于定义配置类,可替换 xml 配置文件,被注解的类内部包含有一个或多个被 @Bean 注解的方法。这些方法将会被 AnnotationConfigWebApplicationContext 或 AnnotationConfigApplicationContext 类进行扫描,并构建 Bean 定义,初始化 Spring 容器。
  • @Configuration 注解作用在类、接口(包含注解)上
  • @Configuration 注解作用的类不能是 final 类型
  • @Configuration 不可以是匿名类
  • @Configuration 注解中有 @Component 注解的加持,因此它自己本身也是一个 bean 对象,可以通过 Context 的进行获取
  • 嵌套的 @Configuration 类必须是 static 的
  • @Configuration 注解最常见的搭配使用有两个:@Bean 和 @Scope
  • @Bean:等价于 Spring 中的 bean 标签用于注册 bean 对象的,给容器中添加组件,一般以方法名作为组件的 id,配置类里面使用 @Bean 标注在方法上给容器注册组件,默认是单实例的
  • @Scope:用于声明该 bean 的作用域,作用域有 singleton、prototype、request、session

示例代码

https://gitee.com/alfredinchange/springboot.git 下 com.alfred.springboot.configuration

参考资料(感谢)

posted @ 2024-11-20 19:29  临渊启明  阅读(28)  评论(0)    收藏  举报