Christian Rockrohr
Christian Rockrohr

Reputation: 1045

How to create temp properties file for Spring propertyPlaceholderConfigurer within Junit

I am writing a small UnitTest to ensure that my properties fallback mechanism works as expected. My idea was, to programmaticaly create a properties file somewhere in the filesystem and then let Spring access this file to load props from this point.

Problem is, that spring does not see/read the file even though, it is there (Windows explorer shows and opens the file)

File createn:

try {
        // Create temp file.
        // File file = File.createTempFile("temp", ".properties");
        File file = new File("C:/temp/temp.properties");

        // den aktuellen Pfad in eine Umgebungsvariable setzen, damit sie von der SpringConfig ausgelesen werden kann.
        System.out.println(file.getAbsolutePath());
        System.setProperty("tempPropsFilename", file.getAbsolutePath());

        // Delete temp file when program exits.
        file.deleteOnExit();

Spring config

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- Die Position der Datei in der Liste ist wichtig. Die letzte überschreibt 
            die erste (natürlich nur die props, die in beiden enthalten sind) -->
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <array>
                <value>${tempPropsFilename}</value>
            </array>
        </property>
    </bean>

Error message from Spring

    06-07@09:45:48 [main  ] INFO  (                 PropertiesLoaderSupport.java:177) config.PropertyPlaceholderConfigurer     - Loading properties file from class path resource [C:/temp/temp.properties]
06-07@09:45:48 [main  ] WARN  (                 PropertiesLoaderSupport.java:200) config.PropertyPlaceholderConfigurer     - Could not load properties from class path resource [C:/temp/temp.properties]: class path resource [C:/temp/temp.properties] cannot be opened because it does not exist

Upvotes: 1

Views: 1300

Answers (2)

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

Try using

<property name="location" value="file:/${tempPropsFilename}"/>

It should make Spring search in file system not a classpath.

Resources documentation

Upvotes: 1

DaveH
DaveH

Reputation: 7335

As far as I remember, File(path) creates an abstract representation of the file - it doesn't write anything to disc

If you remove the file.deleteOnExit() does the file exist on disc?

Try writing to the file - I think that will commit it to disc.

Upvotes: 0

Related Questions