常用注解——属性绑定(@ConfigurationProperties,@EnableConfigurationProperties)

103 阅读1分钟

使用注解将IOC容器中的任意组件(bean)的属性值和application.properties配置文件进行绑定

  1. 给容器中注册组件(@Component(在实体类上申明)、@Bean(在配置类中注册组件))
  2. @ConfigurationProperties 声明组件和配置文件的哪些配置项进行绑定( @ConfigurationProperties中perfix属性值要和application.properties前缀名一致)
使用Componet注解
image.png
使用Bean注解
@ConfigurationProperties 既可以标明类也可以标明方法
image.png

当导入第三方jar包时要属性绑定可以用@EnableConfigurationProperties

/\*\*

*   EnableConfigurationProperties
*   1.开启Sheep组件的属性绑定
*   2.默认把这个组件放入IOC容器中
    \*/

@EnableConfigurationProperties(Sheep.class)//导入第三方写好的组件进行属性绑定
//SpringBoot默认只扫描主程序所在的包。如果导入第三方包,即使组件上标注了@Componet,@ConfigurationProperties也没用
@SpringBootApplication//这位是一个配置类,配置本身也是容器中的组件
public class AppConfig02 {
@Bean
@ConfigurationProperties(prefix = "pig")
public Pig pig01(){
return new Pig();
}
}