The documentation says that the ValidatorFactory is thread-safe, but I have a concern about using the annotated service “InvService” as shown below, as a class property.
I am wondering if this approach is thread-safe? I basically need to do a database lookup based on the constraint violation.
public class MyValidator {
@Autowired
InvService invService; // ??????
private final ValidatorFactory factory;
public MyValidator() {
factory = Validation.buildDefaultValidatorFactory();
}
public <T> void validate(final T instance) {
final Validator validator = factory.getValidator();
final Set<ConstraintViolation< T>> violations = validator.validate(instance, Default.class);
if (!violations.isEmpty()) {
final Set<ConstraintViolation<?>> constraints = new HashSet<ConstraintViolation<?>>(violations.size());
for (final ConstraintViolation<?> violation : violations) {
constraints.add(violation);
}
getDBRecords(constraints);
throw new ConstraintViolationException(constraints);
}
}
private getDBRecords(Set<ConstraintViolation<?>> constraints) {
invService.get(....);
}
}
This is what the service class looks like:
@Service
public class InvServiceImpl implements InvService {
@Autowired
private InvDAO InvDAO;
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public <T extends InvContent> getProduct(String InvKey) {
return InvDAO.getInvContent(InvKey, TYPEPROD, Product.class);
}
}
That depends… is InvService thread-safe? If it is, then you are OK. Thread-safe classes may reference instances of other thread-safe classes as attributes and remain thread-safe themselves. But you have to be sure that the object you are referencing is thread safe. If you did not develop the class, I would want to see documentation that explicitly says it is thread-safe.