Immutable @ConfigurationProperties

后端 未结 7 1906
误落风尘
误落风尘 2020-12-08 13:55

Is it possible to have immutable (final) fields with Spring Boot\'s @ConfigurationProperties annotation? Example below

@ConfigurationProperties(         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 14:12

    From Spring Boot 2.2, it is at last possible to define an immutable class decorated with @ConfigurationProperties.
    The documentation shows an example.
    You just need to declare a constructor with the fields to bind (instead of the setter way) and to add the @ConstructorBinding annotation at the class level to indicate that constructor binding should be used.
    So your actual code without any setter is now fine :

    @ConstructorBinding
    @ConfigurationProperties(prefix = "example")
    public final class MyProps {
    
      private final String neededProperty;
    
      public MyProps(String neededProperty) {
        this.neededProperty = neededProperty;
      }
    
      public String getNeededProperty() { .. }
    }
    

提交回复
热议问题