read property files in Spring

Jun 17, 2014 00:00 · 225 words · 2 minute read Programming Java Spring

What are properties files ?

Properties files help us to abstract out values from our project e.g. url , passwords. Moving away from hardcoding these values in the source code can help us to move our code easily between different environments.

how to read property file from Spring xml configuration

create a property file

make a file and name it anything e.g. app.someProperties and put your key value pairs there

property file

someValue = none environment name

set your property file location in the config

Add property placeholder element and set your property file location.

config file

<context:property-placeholder location="app.someProperty"/>

read values

To read values you need to set the “Value” annotation on the variable.

value annotation

@Value("${someValue}")
private String someValue;

Download

Feel free to download the full source code of this example from my github.

how to read property file from Spring java configuration

Similar to xml configuration you need to create property file.

map config file to property file

set the address of the property file in the config file.

property source

@PropertySource("app.someProperties")

load the configure file in the config file with a getter.

configure file

@Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

To read the value use the “Value” annotation similar to the xml configuration.

Download

Feel free to download the full source code of this example from my github.