Hello,
I know, I have not been writing on my blog since a long time, but, I have been very busy with a challenge project. So, today, I start with a mini-post concerning the use of JVM variable/argument. We will study a concret example to specifiy the place of a configuration file outside of classpath scope.
Needs
We need to precise the place of a configuration file without hard code its path in the application.
Our properties file is MyConfigFile.properties with the simple content:
1 | # ########## Comment ######## |
2 | my.config.property123=val123 |
3 | my.config.property465=val465 |
… but, how specify the path of this file in Spring XML configuration file (placeholder)? in Java code?
Set the JVM argument
The solution is use of JVM argument, which doesn’t need to modify the application deliveries.
The setting of JVM argument/variable is done during the starting of AS, below the example in TOMCAT server configuration edition:

1 | -Dmyconfigfile="file:/projects/config/MyConfigFile.properties" |
…in this example, we have create a variable myconfigfile to specify the path to a configuration file named MyConfigFile.properties.
Note:
The “file:/” notation precise that it is a path to file. For example file:/C:/projects/config/MyConfigFile.properties, file:/C:\\projects\\config\\MyConfigFile.properties are possible. But, with a value of variable like file:/projects/config/MyConfigFile.properties the properties file must be on the same disk drive than the JRE installation folder. For example, if your used JRE is installed in C:\Program Files (x86)\Java\jre6, then, your properties MyConfigFile.properties file must be in C:\projects\config\.
Use of JVM variable in the Spring
The use of JVM variable in the Spring XML configuration file is very simple:
…like this example of PropertyPlaceholderConfigurer:
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
20 | < context:property-placeholder location = "${myconfigfile}" > |
Use of JVM variable in Java
The use of JVM variable in the Java code is very simple:
1 | String configFile = System.getProperty( "myconfigfile" ); |
…like in the following example:
05 | String configFile = System.getProperty( "myconfigfile" ); |
23 | ResourceLoader resourceLoader = new DefaultResourceLoader(); |
24 | Resource resource = resourceLoader.getResource(configFile); |
26 | in = resource.getInputStream(); |
33 | Properties result = new Properties (); |
39 | DefaultPropertiesPersister propPersist = new DefaultresourceLoader(); |
40 | propPersist.load(result, new InputStreamReader(resource.getInputStream()); |
48 | Object value = result.get( "my.config.property123" ); |
That’s all!!!
Huseyin OZVEREN
Related