在Spring Boot中,读取配置是非常常见且重要的一个功能,它允许应用从外部(如配置文件、环境变量、命令行参数等)灵活地获取配置信息。Spring Boot提供了多种方式来读取配置,以下是几种常用的方法:

1. 使用@Value注解

@Value注解是最直接的方式来读取配置文件中的值。可以将它用在字段上、setter方法上,甚至是构造器上。如果配置文件没有,会报错,可以使用“:”在后面设置默认值。

@Component
public class MyBean {

    @Value("${some.property:someProperty}")
    private String someProperty;

    // getter 和 setter 省略
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
2. 使用@ConfigurationProperties注解

@ConfigurationProperties提供了一种更为强大和灵活的方式来读取配置。它允许将配置文件的属性绑定到一个Bean上,并且支持复杂的类型(如List、Map等)。

首先,定义一个配置类:

@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private String name;

    private List<String> servers = new ArrayList<>();

    // getter 和 setter 省略
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

然后,在application.propertiesapplication.yml中配置:

# application.properties
my.name=myAppName
my.servers[0]=localhost:8080
my.servers[1]=localhost:8081
  • 1.
  • 2.
  • 3.
  • 4.

或者YAML格式:

# application.yml
my:
  name: myAppName
  servers:
    - localhost:8080
    - localhost:8081
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
3. 使用Environment接口

Environment接口提供了检查不同源(如系统属性、环境变量和配置文件)中属性的能力。可以注入Environment对象到Bean中,然后使用它来获取配置。

@Component
public class MyBean {

    private final Environment env;

    @Autowired
    public MyBean(Environment env) {
        this.env = env;
    }

    public void printProperty() {
        String property = env.getProperty("some.property");
        System.out.println(property);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
4. 使用@PropertySource注解

如果需要从一个非标准的配置文件中读取属性,可以使用@PropertySource注解。这个注解允许指定一个或多个属性文件的位置,这些文件将作为Spring Environment的附加属性源。

@Configuration
@PropertySource("classpath:mycustom.properties")
public class MyAppConfig {

    @Value("${some.custom.property}")
    private String someCustomProperty;

    // 使用 someCustomProperty
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
5. 使用Spring Cloud Config

对于微服务架构,Spring Cloud Config提供了一个客户端和服务器端的解决方案,用于外部化配置。服务器存储配置信息(在git、文件系统或SVN中),而客户端(应用)通过HTTP请求从服务器获取配置。这种方式适用于复杂或动态变化的配置需求。

总结

Spring Boot提供了多种灵活的方式来读取配置,从简单的@Value注解到复杂的@ConfigurationProperties,再到支持从外部源(如Spring Cloud Config)动态获取配置。根据具体需求选择最适合的方法。

SpringBoot中读取配置的几种方法总结_环境变量