【问题标题】:Spring boot. The profit of using @ConfigurationProperties annotation弹簧靴。使用@ConfigurationProperties 注解的好处
【发布时间】:2019-10-21 05:42:31
【问题描述】:

你能解释一下使用@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 个设置器)。

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

【问题讨论】:

    标签: java spring configuration annotations


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      【解决方案2】:

      @ConfigurationProperties 是外部化配置的注解。要将属性值从属性文件注入到类中,我们可以在类级别添加 @ConfigurationProperties

      【讨论】:

        【解决方案3】:

        使用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
        }
        

        【讨论】:

          猜你喜欢
          • 2021-04-10
          • 2017-12-22
          • 2018-02-14
          • 2019-05-03
          • 2021-04-20
          • 1970-01-01
          • 2023-01-07
          • 1970-01-01
          • 2021-12-08
          相关资源
          最近更新 更多