Spring开机。使用@ConfigurationProperties 注解的好处

Spring boot. The profit of using @ConfigurationProperties annotation

你能解释一下使用@ConfigurationProperties 注释的好处吗?

我必须选择我的代码。

首先使用@ConfigurationProperties 注解:

@Service
@ConfigurationProperties(prefix="myApp")
public class myService() {
  private int myProperty;
  public vois setMyProperty(int myProperty) {
    this.myProperty = myProperty;
  }
  // And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
}

第二个没有@ConfigurationProperties注解。

看起来像这样:

@Service
public class myService() {
    private final Environment environment;
    public myService(Environment environment) {
        this.environment = environment;
    }
  // And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
  environment.getProperty("myApp.myProperty")
}

使用一个 属性 代码量看起来是一样的,但是如果我有大约 10 个属性,第一个选项将有更多的代码样板(为此属性定义 10 个属性和 10 个设置器)。

第二个选项将只注入一次环境,不添加样板代码。

@ConfigurationProperties 用于映射属性文件中具有 Class 属性的一组属性。使用 @ConfigurationProperties 使您的代码更具可读性、分类/模块化和更清晰。怎么样?

  1. 您已将应用程序属性映射到 POJO bean 并确保可重用性。

  2. 您正在使用带抽象的 spring bean(自动注入属性)。

现在,如果您使用 Environment bean,您将始终必须调用 getProperty,然后指定 属性 的字符串名称,因此有很多样板代码。另外,如果你必须重构一些 属性 并重命名它,你必须在所有使用它的地方都这样做。

因此,我的建议是,当您必须对属性进行分组并在多个地方重复使用时,请选择 @ConfigurationProperties。如果您必须使用一个 属性 或两个并且在整个应用程序中仅在一个地方使用,则可以使用环境。

@ConfigurationProperties 是外化配置的注解。要将 属性 值从 属性 文件注入到 class,我们可以在 class 级别 [=10] 添加 @ConfigurationProperties =]

使用 ConfigurationProperties 时,您无需记住 属性 名称即可检索它。 Spring 负责映射。例如:

app.properties.username-max-length 属性

将映射到

String usernameMaxLength POJO

您只需要 usernameMaxLength 字段名称正确一次。

使用ConfigurationProperties 使您的代码易于测试。您可以为不同的测试场景拥有多个属性文件,并可以在您的测试中使用它们 TestPropertySource("path").

现在,如果样板 getters/setters 困扰您。您始终可以使用 lombok's @Getter/@Setter。这只是一个建议,取决于个人的选择。

另外,从Spring Boot 2.2.0开始,你的@ConfigurationProperties类可以是不可变的

@ConfigurationProperties(prefix = "app.properties")
public class AppProperties {

    private final Integer usernameMaxLength;

    @ConstructorBinding
    public AppProperties(Integer usernameMaxLength) {

        this.usernameMaxLength = usernameMaxLength;
    }

    // Getters
}