In this tutorial we will see how to add our own properties to Spring Environment programmatically.
Environment
contact-person=Monica J. Pace
package com.logicbig.example; 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"); } } }
-- property sources --name = systemPropertiessource = class java.util.Propertiesname = systemEnvironmentsource = class java.util.Collections$UnmodifiableMapname = class path resource [app.properties]source = class java.util.Properties-- accessing app.properties --contact-person: Monica J. Pace
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.