带有spring mvc的scala中的JSR 303 ConstraintValidator

时间:2015-10-21 18:23:52

标签: java scala spring-mvc bean-validation

我混合了scala-java spring-boot mvc项目。我正在尝试使用javax.validation.ConstraintValidator实现请求bean的自定义验证器 我在这里阅读其他线程,最好在Java Does scala suport JSR-303 validation?

中编写注释

我在Java中编写了自定义Constraint注释,在scala中编写了ConstraintValidator类,但是当我指定@Constraint(validatedBy = ScalaCustomerValidator.class)时,它给出了Type mismatch: cannot convert from Class<ScalaCustomerValidator> to Class<? extends ConstraintValidator<?,?>>[]的编译错误。我的ScalaCustomerValidator确实扩展了ConstraintValidator。

// java的

@Constraint(validatedBy = ScalaCustomerValidator.class) //Type mismatch error 
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ScalaCustomerValid {
    String message() default "Invalid tab to filter combination";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

// ConstraintValidator的scala定义

class ScalaCustomerValidator extends ConstraintValidator[ScalaCustomerValid, ScalaCustomer] { .. }

javap输出:

javap ScalaCustomerValidator
Warning: Binary file ScalaCustomerValidator contains com.ScalaCustomerValidator
Compiled from "ScalaCustomerValidator.scala"
public class com.ScalaCustomerValidator implements javax.validation.ConstraintValidator<com.ScalaCustomerValid, com.ScalaCustomer> {
  public void initialize(com.ScalaCustomerValid);
  public boolean isValid(com.ScalaCustomer, javax.validation.ConstraintValidatorContext);
  public boolean isValid(java.lang.Object, javax.validation.ConstraintValidatorContext);
  public void initialize(java.lang.annotation.Annotation);
  public com.ScalaCustomerValidator();
}

1 个答案:

答案 0 :(得分:1)

你的问题是由于不可能获得scala对象的类。 Scala编译器为对象ScalaCustomerValidator生成名为ScalaCustomerValidator $的类。 ScalaCustomerValidator $实际上实现了ConstraintValidator,并且没有办法引用它的类。 如果您尝试使用scala:

val cl = classOf[ScalaCustomerValidator]

你也会收到编译错误。

此问题仍然存在:https://issues.scala-lang.org/i#browse/SI-2453