Environment and Properties



Using Environment object you can easily get the value of any key defined in the .properties file

Using @PropertySource("path_of_the_source")  you can provide the .properties file name from where you want to read the key-value pairs.

@Configuration
@PropertySource("classpath:/com/myapp/application.properties")
public class AppConfig {
@Autowired
Environment env;


public String getProperty(String key){
      env.getProperty(key);
}
}

There are different flavour of the getProperty method available in spring
1) String getProperty(String key)
This method will return the String value of the provided key

2) String getProperty(String key, String defaultValue)
This method will also return the String value of the provided key but if the value is not available then it will return the provided default value in the second argument

3) T getProperty(String key, Class<T> type)
This method will return the value for the provided key by converting it in the provided class type in the second argument in the method.

4) T getProperty(String key, Class<T> type, T defaultValue)
This method will return the value for the provided key by converting it in the provided class type in the second argument in the method. but if the value is not available then it will return the provided default value.

Accept the getProperty method there are also method available for getting profile information
1) String[] getActiveProfiles()
This method Returns an array of the  active profile names

2) String[] getDefaultProfiles()
This method Returns an array of the default profile names.