Here is how I derive a Properties object from Spring's Environment. I look for property sources of type java.util.Properties, which in my case will give me system properties and application properties.
@Resource private Environment environment; @Bean public Properties properties() { Properties properties = new Properties(); for (PropertySource<?> source : ((ConfigurableEnvironment) environment).getPropertySources()) { if (source.getSource() instanceof Properties) { log.info("Loading properties from property source " + source.getName()); Properties props = (Properties) source.getSource(); properties.putAll(props); } } return properties; }
Note however that the order may be significant; you would probably want to load the system properties after other properties, so they can override application properties. In that case, add some more control code using source.getName() to pick out "systemProperties":
@Bean public Properties properties() { Properties properties = new Properties(); Properties systemProperties = null; for (PropertySource<?> source : ((ConfigurableEnvironment) environment).getPropertySources()) { if (source.getSource() instanceof Properties) { if ("systemProperties".equalsIgnoreCase(source.getName())) { log.info("Found system properties from property source " + source.getName()); systemProperties = (Properties) source.getSource(); } else { log.info("Loading properties from property source " + source.getName()); Properties props = (Properties) source.getSource(); properties.putAll(props); } } } // Load this at the end so they can override application properties. if (systemProperties != null) { log.info("Loading system properties from property source."); properties.putAll(systemProperties); } return properties; }
application.propertiesEnvironmentyou can get the properties, but it doesn't have a list of all properties. you only can useenv.getProperty("propertyName")to get the propertyEnvironmentis very likely aConfigurableEnvironment, which allows you to iterate the property sources, and you can iterate the properties of anyPropertySourcethat is anEnumerablePropertySource. --- The advantage of usingEnvironmentis that you gain support for features like Profiles and YAML. But the question is: Why do you need to iterate them? Don't you know the names of the properties that are of interest to you?