user1491636 user1491636 - 5 months ago 25
Java Question

Spring Boot - making configuration final

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?

Answer

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;
  }

 }