读取属性配置文件的五种方式

读取属性配置文件的五种方式
  • @Value
  • @ConfigurationProperties
  • @PropertySource + @Value
  • @PropertySource + ConfigurationProperties
  • org.springframework.core.env.Environment

@Configuration和@Compent作用类似一个属于springBoot一个属于spring

application.yml下:

获取配置文件属性值

@ConfigurationProperties(prefix = “spring.redis”) 可以批量注入

读取属性配置的示例

属性配置文件

application.properties

demo.properties

方式一:使用注解@Value读取属性配置

使用此种方式,如无其他需求,可不写setter、getter方法。

方式二:使用注解@ConfigurationProperties读取属性配置

使用此种方式,必须要有成员变量的setter、getter方法。

方式三:使用注解 @PropertySource 和 @Value 来读取属性配置

注:使用@PropertySource注解读取属性配置,该种方式不支持读取yml配置文件

方式四:使用注解 @PropertySource 和 @ConfigurationProperties 来读取属性配置

方式五:使用环境变量 Environment 读取属性配置

测试类