Java Spring: Injecting a value from a property file

If you are using Spring in your Java application you can inject values from a configuration file directly into an instance that holds these values. Other parts of your code can then use this configuration holder. It acts like a facade because the complexity where the configuration values actually come from – maybe from a text file or a database – should not be important for the one consuming the config values.

Spring setup

We have got an almost empty applicationContext.xml file and an environment.properties file that holds the configuration values we need to use in our application.

webservice.url=http://localhost:8080/webservice-path
webservice.username=testuser
webservice.password=secret

Then there is a class that I called ConfigService which is similar to a Java bean class with getter methods for the different configuration values. The class itself has the annotation @Configuration and @PropertySource that points to the property file. Every relevant property in the class has a @Value annotation which in turn points to the respective key in the property file.

@Configuration
@PropertySource("classpath:environment.properties")
public class ConfigService {

	@Value("${webservice.url}")
	private String webserviceUrl;
	@Value("${webservice.username}")
	private String webserviceUsername;
	@Value("${webservice.password}")
	private String webservicePassword;

	public String getWebserviceUrl() {
		return webserviceUrl;
	}

	public String getWebserviceUsername() {
		return webserviceUsername;
	}

	public String getWebservicePassword() {
		return webservicePassword;
	}
}

I have setup a Main class for testing purposes that holds the following code:

try (ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml")) {
	final ConfigService configService = context.getBean(ConfigService.class);
	System.out.println("URL      : " + configService.getWebserviceUrl());
	System.out.println("Username : " + configService.getWebserviceUsername());
	System.out.println("Password : " + configService.getWebservicePassword());
}

The Spring application context is loaded with a try-with-resources statement which makes sure that the context will be closed after the try block. Then we load the ConfigService bean from the context and can access the configuration values by calling the getter methods.

The whole setup is pretty static but should be sufficient to handle the configuration in smaller applications. It is at least better to do it this way instead of hard coding certain string in your application – for example if you have too many static final strings in your classes that need to be changed depending on the deployment scenario this might be an easy alternative for you.