Java 弹簧靴。使用@ConfigurationProperties注释的好处

Java 弹簧靴。使用@ConfigurationProperties注释的好处,java,spring,configuration,annotations,Java,Spring,Configuration,Annotations,你能解释一下使用@ConfigurationProperties注释的好处吗 我必须选择我的代码 首先使用@ConfigurationProperties注释: @Service @ConfigurationProperties(prefix="myApp") public class myService() { private int myProperty; public vois setMyProperty(int myProperty) { this.myProperty

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


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

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

  • 您将应用程序属性映射到pojobean,从而确保可重用性

  • 您正在使用Springbean进行抽象(自动注入属性)

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


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

    @ConfigurationProperties是外部化配置的注释。要将属性值从属性文件注入到类中,我们可以在类级别添加@ConfigurationProperties,使用
    ConfigurationProperties
    时,您无需记住属性名称即可检索它。Spring负责映射。例如:

    app.properties.username最大长度
    属性中

    将映射到

    POJO中的字符串usernameMaxLength

    只需将
    usernameMaxLength
    字段名设置正确一次

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

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

    此外,从开始,您的
    @ConfigurationProperties
    类可以是不可变的

    @ConfigurationProperties(prefix=“app.properties”)
    公共类AppProperties{
    私有最终整数usernameMaxLength;
    @构造绑定
    公共AppProperties(整数usernameMaxLength){
    this.usernameMaxLength=usernameMaxLength;
    }
    //吸气剂
    }