Im getting this error on resource:
Potential resource leak: 'factory' may not be closed at this location
This is my code:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<RenewPackageRequest>> violations = validator.validate(request);
if (CollectionUtils.isNotEmpty(violations)) {
error.throwValidationError(null, "Input parameters can't be null/empty");
} else if (!YES.equalsIgnoreCase(request.getRenewPackage()) && !NO.equalsIgnoreCase(request.getRenewPackage())) {
error.throwValidationError("RenewPackage", "parameter can only be YES/NO");
}
return resource;
I want to use try with resources but i dont know how to use. I now that if i put factory.close() this error will disappear but this is not good praxis. Any suggestion?
CodePudding user response:
I want to use try with resources but i dont know how to use.
The java Try-with-Resources Statement has a really simple syntax of
try (<declaration of closable resources>) {
// code where you use those resources
}
So in your case a simple
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory();) {
Validator validator = factory.getValidator();
Set<ConstraintViolation<RenewPackageRequest>> violations = validator.validate(request);
if (CollectionUtils.isNotEmpty(violations)) {
error.throwValidationError(null, "Input parameters can't be null/empty");
} else if (!YES.equalsIgnoreCase(request.getRenewPackage()) && !NO.equalsIgnoreCase(request.getRenewPackage())) {
error.throwValidationError("RenewPackage", "parameter can only be YES/NO");
}
return resource;
}
should work.