gpt4 book ai didi

java - Spring 框架的验证无法与 JSR-303 验证一起使用

转载 作者:行者123 更新时间:2023-12-01 19:28:28 25 4
gpt4 key购买 nike

我的问题与 Bean 验证有关。显然 SpringBoot 带有两种不同的验证机制,其一 JSR-303 compilant(在 javax.validation 包中)和 Spring 框架提供的其他(在 org.springframework.validation 包中)。

虽然很容易执行 JSR-303通过 @Validated 进行验证和@Valid注解,我找不到Spring的注解的正确方法。

采取以下User bean 。

@Entity
public class User {
@Column
@Id
private String id;

@Column(unique = true)
@Username
private String username;

// [...]
}

哪里@Username约束定义如下。基本上,它只是 @Pattern 的组合。和@Size约束条件。

@Constraint(validatedBy = {})
@Documented
@Pattern(regexp = "[A-Za-z0-9_]+")
@Retention(RUNTIME)
@Size(max = 24, min = 3)
@Target(FIELD)
public @interface Username {
String message() default "";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

User beans 存储在名为 UserRepository 的存储库中,定义如下。

@Repository
public interface UserRepository extends CrudRepository<User, String>, JpaSpecificationExecutor<User> {
}

为了访问存储库,我编写了一个服务,如下所示。

@Transactional
@Service
public class UserService {
@Autowired
private UserRepository userRepository;

@Validated
public void create(@Valid User user) {
userRepository.save(user);
}
}

到目前为止,一切都非常整洁并且一切正常。只需几个注释,我就实现了一切。

现在,我有了另一个 validator (不是 JSR-303 )。

// [...]
import org.springframework.validation.Validator;

@Component
public class UniqueUsernameValidator implements Validator {
@Autowired
private UserRepository userRepository;

@Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object target, Errors errors) {
User user = (User) target;

if (userRepository.count(where(usernameIsEqualTo(user.getUsername()))) > 0) {
errors.rejectValue("username", "username.exists");
}
}
}

理想情况下,我希望通过相同的 @Validated 强制执行它和@Valid注释,但到目前为止我一直不走运。我想这绝对是可能的,因为类 org.springframework.validation.Validator 的文档说

This interface is totally divorced from any infrastructure or context; that is to say it is not coupled to validating only objects in the web tier, the data-access tier, or the whatever-tier. As such it is amenable to being used in any layer of an application, and supports the encapsulation of validation logic as a first-class citizen in its own right.

最佳答案

@Valid 是一个 JSR-303 bean 验证注释,它不会调用您的 UniqueUsernameValidator Spring Validator。

如果您想在服务中执行此操作,则需要手动调用它:

public void create(@Valid User user) {
Errors errors = new BeanPropertyBindingResult(user, "user");

// Validator component has been previously injected into the service.
uniqueUsernameValidator.validate(user, errors);
if (errors.hasErrors()) {
throw new RuntimeException(errors.toString());
}

userRepository.save(user);
}

关于java - Spring 框架的验证无法与 JSR-303 验证一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com