春季引导。使用@ConfigurationProperties注释的好处

时间:2019-10-21 05:42:31

标签: 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)。

第二个选项将只注入一次Environment,而没有其他样板代码。

3 个答案:

答案 0 :(得分:2)

@ConfigurationProperties用于当您要从具有Class属性的属性文件映射一组属性时。使用@ConfigurationProperties使您的代码更具可读性,分类/模块化和更简洁。怎么样?

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

  2. 您正在使用Spring bean进行抽象(属性会自动注入)。

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用12:00 21:30 时,您无需记住要检索的属性名称。 Spring负责映射。例如:

ConfigurationProperties在属性

将被映射到

app.properties.username-max-length在POJO中

您只需要一次正确设置String usernameMaxLength字段名称即可。

使用usernameMaxLength使代码易于测试。您可以为不同的测试场景提供多个属性文件,并可以在ConfigurationProperties的测试中使用它们。

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

此外,从Spring Boot 2.2.0开始,您的@Setter类是不可变的

@ConfigurationProperties