1

My Spring Boot (1.3.5) application uses externalized configuration using an application.properties file. Alongside, I currently have a configuration class as such:

@Configuration
MyConfig {
   @Value("${prop}")
   private String prop;

   // getters
}

I'm wondering if there is a way to make prop final. Ideally I'd like to access my configuration properties publicly; for example myConfig.prop. I'd like to make all properties public and final; however I believe configuration classes are first instantiated via an empty constructor before properties are loaded. Is there an alternative approach?

duffymo
  • 305,152
  • 44
  • 369
  • 561
user1491636
  • 2,355
  • 11
  • 44
  • 71

2 Answers2

1

You can inject your config values in the constructor and assign to a final field.

@Configuration
class MyConfig {
  private String final prop;
  public MyConfig(@Value("${prop}") String prop){
    this.prop = prop;
  }

 }
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

For all the people landing here and asking themself the same question, please have a look at https://stackoverflow.com/a/57191291/11770752

In addition you can use this with lombok if desired, which reduces the class' boilerplate code.

anjey
  • 93
  • 2
  • 11
  • 1
    The solution won't work for Spring Boot version 1.3.6 (specified in the question). – Petr Aleksandrov Nov 30 '20 at 11:52
  • you are right, just in case anybody for new versions (assuming which is the most part of the user) was curious i wanted them to provide further information. if this is somewhat bad, i'll excuse myself. – anjey Nov 30 '20 at 11:58