使用前言:

在spring开发过程中我们常使用到@ConfigurationProperties注解,通常是用来将properties和yml配置文件属性转化为bean对象使用。

application.yml:

@EnableConfigurationProperties注解作用

跟配置文件相对应的自定义类:

@EnableConfigurationProperties注解作用

以上步骤可以将配置文件属性注册到IOC容器中,在获取这些bean之前,首先需要使用@EnableConfigurationProperties({ConfigBean.class})  注解使ConfigurationProperties注解生效:

@EnableConfigurationProperties注解作用

至此就可以获取自定义的注解bean对象

@EnableConfigurationProperties注解作用

测试所得结果:

@EnableConfigurationProperties注解作用

除了上述方式之外,还可以@ConfigurationProperties注解的类加上@Component注解也可以将@ConfigurationProperties注解的类注入到spring容器中。

@EnableConfigurationProperties注解作用

注:@Component注解表明一个类会作为组件类,然后spring会为该类创建bean。

  @Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。

 

 

转摘:https://www.cnblogs.com/JamieLove/p/11180679.html

相关文章: