Close

Spring Framework - ConfigurableEnvironment Examples

Spring Framework 

Using ConfigurableEnvironment interface to access properties:

One of the feature defined by the interface ConfigurableEnvironment, is to manage underlying property sources. This example demonstrate how to access system, environmental and application provided property sources using ConfigurableEnvironment.

public class DefaultSystemSourcesExample {
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
ConfigurableEnvironment env = context.getEnvironment();
printSources(env);
System.out.println("-- System properties --");
printMap(env.getSystemProperties());
System.out.println("-- System Env properties --");
printMap(env.getSystemEnvironment());
}

private static void printSources (ConfigurableEnvironment env) {
System.out.println("-- property sources --");
for (PropertySource<?> propertySource : env.getPropertySources()) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass()+"\n");
}
}


private static void printMap (Map<?, ?> map) {
map.entrySet()
.stream().limit(15)
.forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
System.out.println("-------------");

}
}
Original Post




import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;
import java.io.IOException;

public class UserPropertySourceExample {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
ConfigurableEnvironment env = context.getEnvironment();
env.getPropertySources().addLast(new ResourcePropertySource(new ClassPathResource("app.properties")));
printSources(env);
String contactPerson = env.getProperty("contact-person");
System.out.println("-- accessing app.properties --");
System.out.println("contact-person: " + contactPerson);
}

private static void printSources(ConfigurableEnvironment env) {
System.out.println("-- property sources --");
for (PropertySource<?> propertySource : env.getPropertySources()) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
}
}
Original Post




See Also