Scala是否支持JSR-303验证?
scala是否支持JSR-303验证?
Does scala supports JSR-303 validation?
如果是-您能举个例子吗?
如果不是-是否有解决方法可在scala类上运行JSR-303验证?
If it does not - are there workarounds to run JSR-303 validation on scala classes?
好消息和坏消息.
好消息是,您可以毫无问题地在Scala代码中使用JSR-303批注.
The good news is that you can use JSR-303 annotations in your Scala code with no problems.
这是我以前的项目中的一个示例,其中所有注释都是JSR-303注释,其中一些是开箱即用的,其中一些是自定义的.
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 = _
}
请注意msgs
集合是java.util.List
的方式.它必须是Java集合,@NotEmpty
和@Valid
才能正常工作.但是使用JavaConverters
将该字段公开为Scala集合很容易.
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
.
坏消息是您不能使用Scala创建JSR-303批注.您必须使用Java编写这些注释.因此,如果要编写自定义JSR-303批注,则需要混合使用Scala/Java项目.
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.
Scala中有一个旧错误(错误#32!)错误跟踪器以支持这些类型的注释,但由于无法修复,因此目前已关闭.请继续投票.
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.