Does scala suport JSR-303 validation?

我与影子孤独终老i 提交于 2019-11-30 23:44:47

There is good news and bad news.

The good news is that you can use JSR-303 annotations in your Scala code with no problems.

Here is an example from a previous project of mine, where all of the annotations are JSR-303 annotations, some of them out of the box, some of them custom.

@MessagesValid
class Messages {
  @NotEmpty @Valid
  private var msgs: java.util.List[DeliveredMessage] = _  
  def messages = msgs.asScala

  @ChannelValid 
  var channel: String = _

  var emailFrom: String = _
  var emailReplyTo: String = _

  @PublishAtValid
  var publishAt: String = _
}

Note how the msgs collection is a java.util.List. It needs to be a Java collection for the @NotEmpty and @Valid to work. But it's easy enough to expose that field as a Scala collection using JavaConverters.

The bad news is that you cannot create a JSR-303 annotation using Scala. You must write those annotations using Java. So you will need to have a mixed Scala/Java project if you want to write custom JSR-303 annotations.

There is an old bug (bug #32!) in the Scala bug tracker to support these types of annotations but it is currently closed as Won't Fix. Please vote for it anyway.

Sure!

However, custom annotations are needed for Scala types, as well as custom handling of collections.

If there is any interest, I'll opensource my implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!