Immutable @ConfigurationProperties

后端 未结 7 1904
误落风尘
误落风尘 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:01

    I have to resolve that problem very often and I use a bit different approach, which allows me to use final variables in a class.

    First of all, I keep all my configuration in a single place (class), say, called ApplicationProperties. That class has @ConfigurationProperties annotation with a specific prefix. It is also listed in @EnableConfigurationProperties annotation against configuration class (or main class).

    Then I provide my ApplicationProperties as a constructor argument and perform assignment to a final field inside a constructor.

    Example:

    Main class:

    @SpringBootApplication
    @EnableConfigurationProperties(ApplicationProperties.class)
    public class Application {
        public static void main(String... args) throws Exception {
            SpringApplication.run(Application.class, args);
        }
    }
    

    ApplicationProperties class

    @ConfigurationProperties(prefix = "myapp")
    public class ApplicationProperties {
    
        private String someProperty;
    
        // ... other properties and getters
    
       public String getSomeProperty() {
           return someProperty;
       }
    }
    

    And a class with final properties

    @Service
    public class SomeImplementation implements SomeInterface {
        private final String someProperty;
    
        @Autowired
        public SomeImplementation(ApplicationProperties properties) {
            this.someProperty = properties.getSomeProperty();
        }
    
        // ... other methods / properties 
    }
    

    I prefer this approach for many different reasons e.g. if I have to setup more properties in a constructor, my list of constructor arguments is not "huge" as I always have one argument (ApplicationProperties in my case); if there is a need to add more final properties, my constructor stays the same (only one argument) - that may reduce number of changes elsewhere etc.

    I hope that will help

提交回复
热议问题