1717package org .springframework .validation .beanvalidation ;
1818
1919import java .io .IOException ;
20+ import java .io .InputStream ;
2021import java .lang .reflect .Constructor ;
2122import java .lang .reflect .Method ;
23+ import java .util .ArrayList ;
2224import java .util .Arrays ;
2325import java .util .HashMap ;
2426import java .util .List ;
@@ -290,13 +292,17 @@ public void afterPropertiesSet() {
290292 if (this .parameterNameDiscoverer != null ) {
291293 configureParameterNameProvider (this .parameterNameDiscoverer , configuration );
292294 }
293-
295+ List < InputStream > mappingStreams = null ;
294296 if (this .mappingLocations != null ) {
297+ mappingStreams = new ArrayList <>(mappingLocations .length );
295298 for (Resource location : this .mappingLocations ) {
296299 try {
297- configuration .addMapping (location .getInputStream ());
300+ InputStream stream = location .getInputStream ();
301+ mappingStreams .add (stream );
302+ configuration .addMapping (stream );
298303 }
299304 catch (IOException ex ) {
305+ closeMappingStreams (mappingStreams );
300306 throw new IllegalStateException ("Cannot read mapping resource: " + location );
301307 }
302308 }
@@ -307,8 +313,25 @@ public void afterPropertiesSet() {
307313 // Allow for custom post-processing before we actually build the ValidatorFactory.
308314 postProcessConfiguration (configuration );
309315
310- this .validatorFactory = configuration .buildValidatorFactory ();
311- setTargetValidator (this .validatorFactory .getValidator ());
316+ try {
317+ this .validatorFactory = configuration .buildValidatorFactory ();
318+ setTargetValidator (this .validatorFactory .getValidator ());
319+ }
320+ finally {
321+ closeMappingStreams (mappingStreams );
322+ }
323+ }
324+
325+ private void closeMappingStreams (@ Nullable List <InputStream > mappingStreams ){
326+ if (!CollectionUtils .isEmpty (mappingStreams )) {
327+ for (InputStream stream : mappingStreams ) {
328+ try {
329+ stream .close ();
330+ }
331+ catch (IOException ignored ) {
332+ }
333+ }
334+ }
312335 }
313336
314337 private void configureParameterNameProvider (ParameterNameDiscoverer discoverer , Configuration <?> configuration ) {
0 commit comments