Skip to main content
Configuration, profiles, conditions · Topic 5 of 5

Environment and property sources

Definition​

The Environment is where Spring looks up settings. It reads several property sources in order (command line, environment variables, files, defaults), and the first source that has the key wins. @Value injects a setting, with an optional default.

Example code​

Reading settings, with a default and an override

import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.MapPropertySource;
import org.springframework.stereotype.Component;

@Component
class MailSettings {
@Value("${mail.host:localhost}") // default used when the setting is missing
String host;

@Value("${mail.port:25}")
int port;
}

@ComponentScan
class Demo {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext();
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("overrides", Map.of("mail.port", "587")));
context.register(Demo.class);
context.refresh();

MailSettings settings = context.getBean(MailSettings.class);
System.out.println(settings.host + ":" + settings.port); // host from the default, port overridden
System.out.println(context.getEnvironment().getProperty("mail.port"));
context.close();
}
}

// Output:
// localhost:587
// 587

Finished this page? Track your progress (saved only in your browser).