引言

在Spring Boot应用中,读取配置是一项基础且重要的任务。Spring Boot提供了多种灵活的方式来读取配置,以满足不同场景下的需求。本文将详细介绍Spring Boot中读取配置的几种常用方法.

1. 使用@Value注解

@Value注解是最直接且常用的读取配置的方式。它可以将配置文件中的属性值注入到Spring管理的Bean的字段中。

@Component
public class MyBean {
          
    @Value("${some.key1}")
    private String someKey1;

     @Value("${some.key2:defaultVal}")
    private String someKey2;

    public void initSomeKey3(@Value("${some.key3}")String key){
          
        ...
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • @Value注解只能读取单个配置进行赋值,无法读取整个配置文件批量赋值
  • 可以在属性名称后面使用冒号(:default-value)的形式添加默认值
  • 只能用于被Spring管理的Bean中使用,或Java配置@Configuration类
  • 可以用于字段、构造函数参数、方法参数和方法上。当将它放在方法上时,Spring容器初始化时会调用该方法,并将配置属性的值作为方法的参数传递进去.

2. 使用ConfigurationProperties注解

ConfigurationProperties注解允许将配置文件的属性绑定到一个Bean上,这样可以更方便地管理和使用配置信息。与@Value注解相比,ConfigurationProperties支持复杂类型的配置,如列表、集合等。

@Component
@ConfigurationProperties(prefix = "some")
public class SomeProperties {
          
    private String key;
    private