文档说 ValidatorFactory 是线程安全的,但我担心使用如下所示的带注释的服务“InvService”作为类属性。
我想知道这种方法是否是线程安全的?我基本上需要根据约束违规进行数据库查找。
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(....);
}
}
这是服务类的样子:
@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);
}
}