java - Spring Boot 。使用@ConfigurationProperties注解的好处

标签 java spring configuration annotations

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

第二个选项将进行一次环境注入(inject),并且不添加样板代码。

最佳答案

当您想要将属性文件中的一组属性与类属性映射时,请使用

@ConfigurationProperties。使用 @ConfigurationProperties 使您的代码更具可读性、分类性/模块化性和简洁性。怎么办?

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

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

现在,如果您使用Environment bean,则始终必须调用getProperty,然后指定属性的字符串名称,因此需要大量样板代码。另外,如果您必须重构某些属性并重命名它,则必须在使用它的所有地方执行此操作。

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

关于java - Spring Boot 。使用@ConfigurationProperties注解的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58480364/

相关文章:

java - 下拉框 - 从 Spring MVC 模型/上下文到使用 freemarker 的表单

java - Spring Security - 无法注销

ruby - Allure to Cucumber in Ruby 中的配置

java - 当主键自动递增时,如何使用 JPA (EclipseLink) 从数据库中获取特定的 "row"?

使用 JDBC 的 Java - 连接太多?

java - 对于 ajax 按钮,如何在 WebElement.click() 之后避免 StaleElementException?

java - 使用 JSF 在新的浏览器窗口中阅读并打开 PDF

java - spring boot redis 操作 throw broken pipe 错误

solr - 跨多个 Solr 4.6 内核共享模式和配置

azure - 刷新 Azure VM 规模集中的凭据/配置