Instead of getting Environment instance by using ConfigurableApplicationContext#getEnvironment() we can directly inject it as a bean.
Environment
ConfigurableApplicationContext#getEnvironment()
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import jakarta.annotation.PostConstruct; @Component public class MyBean { @Autowired private Environment environment; @PostConstruct public void postInit() { System.out.println("-- accessing system properties --"); String tempDir = environment.getProperty("java.io.tmpdir"); System.out.println("System tempDir: "+tempDir); System.out.println("-- accessing user properties --"); String contactPerson = environment.getProperty("contact-person"); System.out.println("contact-person: " + contactPerson); } }
contact-person=Monica J. Pace
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.ConfigurableEnvironment; @Configuration @PropertySource("classpath:app.properties") @ComponentScan public class UserPropertySourceExample { public static void main(String[] args) { new AnnotationConfigApplicationContext(UserPropertySourceExample.class); } }
-- accessing system properties --System tempDir: C:\Users\Joe\AppData\Local\Temp\-- accessing user properties --contact-person: Monica J. Pace
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.