我想创建自己的Hibernate自定义验证器,我想做的是基于从不同上下文(不同的Spring bean)收集的一些信息添加自定义逻辑。
在我的自定义实现中,我试图在Spring bean中添加构造函数并定义验证器,或者使用Autowire注释,但它们都不起作用
自动接线示例:
public class MyCustomValidator implements ConstraintValidator<CustomConstraint, String> {
@Autowired
private MyCustomChecker customChecker;
@Override
public void initialize(CustomConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return true;
}
//get user authenticated properties to perform validation based on the user
AuthenticatedIdentity identity = Context.getAuthenticatedIdentity();
return customChecker.isWhitelisted(identity);
}
}
构造函数示例:
public class MyCustomValidator implements ConstraintValidator<CustomConstraint, String> {
private MyCustomChecker customChecker;
public MetricDataSizeValidator(MyCustomChecker customChecker) {
this.customChecker = customChecker;
}
@Override
public void initialize(CustomConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return true;
}
//get user authenticated properties to perform validation based on the user
AuthenticatedIdentity identity = Context.getAuthenticatedIdentity();
return customChecker.isWhitelisted(identity);
}
}
我已经阅读了official Hibernate doc,但是并不能完全回答我的问题。
我很确定,当您要基于来自不同上下文的一些信息进行验证时,这是一个常见问题,但是我没有找到答案。
我的应用程序正在使用Spring DI,其中我的bean已经像这样初始化过
<bean id="customChecker" class="com.mycomp.CustomChecker">
<constructor-arg>
<value>arg</value>
</constructor-arg>
</bean>
是否有实现此目标的示例?
使MyCustomValidator成为弹跳豆的最简单方法是在类级别添加@Component批注。