Skip to main content

enerally we do not want to hardcode any configuration value in code and want to load it from outside via various methods. Spring provides a neat way to inject configuration values from application.{properties,yaml,yml} through its own @Value Annotation like below

public class ApplicationConfiguration {
@Value(“${your.property.from.properties.file}”)
private String smtpHost;
// rest of the code
}

But unfortunately it fails silently when we try to assign values into static field like below

public class ApplicationConfiguration {
@Value("${your.property.from.properties.file}")
private static String smtpHost; // it will fail silently
// rest of the code
}

But we can assign values through @Value with this nifty trick

public class ApplicationConfiguration {
private static String smtpHost;
@Value("${your.property.from.properties.file}")
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
// rest of the code
}

Bonus Tip

You can pass default configuration value for your properties via @Value annotation like below

public class ApplicationConfiguration {
@Value("${your.property.from.properties.file:''}")
private String smtpHost;
// rest of the code
}

That’s all for now. Stay well, stay safe. 😎