Check exception cause for @PropertySource(ignoreResourceNotFound) support

Prior to this commit, the ignoreResourceNotFound flag in
@PropertySource was ignored by PropertySourceProcessor if a
PropertySourceFactory threw an exception which wrapped an exception
that would otherwise be ignored -- for example, a FileNotFoundException.

To address this issue, this commit updates PropertySourceFactory so
that it catches RuntimeException and IOException and then checks if the
exception or its cause is an "ignorable" exception in terms of
ignoreResourceNotFound semantics.

Closes gh-22276
This commit is contained in:
Sam Brannen
2023-08-05 09:59:24 +03:00
parent 1451f30781
commit 4a81814dbb
3 changed files with 199 additions and 3 deletions

View File

@@ -34,6 +34,7 @@ import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
@@ -44,6 +45,7 @@ import org.springframework.util.ReflectionUtils;
* single {@link PropertySource} rather than creating dedicated ones.
*
* @author Stephane Nicoll
* @author Sam Brannen
* @since 6.0
* @see PropertySourceDescriptor
*/
@@ -88,9 +90,10 @@ public class PropertySourceProcessor {
Resource resource = this.resourceLoader.getResource(resolvedLocation);
addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
}
catch (IllegalArgumentException | FileNotFoundException | UnknownHostException | SocketException ex) {
// Placeholders not resolvable or resource not found when trying to open it
if (ignoreResourceNotFound) {
catch (RuntimeException | IOException ex) {
// Placeholders not resolvable (IllegalArgumentException) or resource not found when trying to open it
if (ignoreResourceNotFound && (ex instanceof IllegalArgumentException || isIgnorableException(ex) ||
isIgnorableException(ex.getCause()))) {
if (logger.isInfoEnabled()) {
logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
}
@@ -150,4 +153,14 @@ public class PropertySourceProcessor {
}
}
/**
* Determine if the supplied exception can be ignored according to
* {@code ignoreResourceNotFound} semantics.
*/
private static boolean isIgnorableException(@Nullable Throwable ex) {
return (ex instanceof FileNotFoundException ||
ex instanceof UnknownHostException ||
ex instanceof SocketException);
}
}