Nicolas Raoul
Nicolas Raoul

Reputation: 60213

Spring import resource: Skip if file does not exist

I added this to my Spring configuration inside my WAR file:

<import resource="classpath:myapp-custom-settings.xml"/>

This way, users can create a myapp-custom-settings.xml file (in a folder listed in shared.loader) to modify the beans they want without having to unzip the WAR.
Very convenient, but most users don't have such a file, in which case a FileNotFoundException happens and the app does not start:

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException:Configuration problem: Failed to import bean definitions from URL location [file:/home/nico/tomcat/conf/myapp-custom-settings.xml]
Offending resource: ServletContext resource [/WEB-INF/spring/root-context.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file:/home/nico/tomcat/conf/myapp-custom-settings.xml]; nested exception is
java.io.FileNotFoundException: /home/nico/tomcat/conf/myapp-custom-settings.xml (No such file or directory)
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:233)

QUESTION: Is there a way to make this import failsafe?
I mean, load the file if it exists, but skip if it does not exist.

Upvotes: 0

Views: 3794

Answers (1)

Nicolas Raoul
Nicolas Raoul

Reputation: 60213

The trick is to use classpath* instead of classpath. Note the * asterisk character.
Example:

<import resource="classpath*:myapp-custom-settings.xml"/>

The app will now start normally even if no myapp-custom-settings.xml file is found.

Upvotes: 7

Related Questions