简体   繁体   English

如何在属性文件的@Size注释中设置最大值?

[英]How to set max value in @Size annotation from properties file?

I'm using Hibernate Validator Version 5.3.0. 我正在使用Hibernate Validator版本5.3.0。

Following is the class I want to validate. 以下是我要验证的课程。

public class DocumentRequest {

    @NotEmpty(message="{invalid.docId}")
    private String docId;

    @NotEmpty(message="{invalid.title}")
    @Size(max=200, message="{invalid.title}")
    private String title;
}

The problem here is the max value of @Size is a "magic" number(Quoting Sonar ). 这里的问题是@Size最大值是一个“魔术”数字(引用Sonar )。 How can I set it from properties file? 如何从属性文件设置它?

I tried to add it as follows: 我尝试将其添加如下:

public class DocumentRequest {

    @NotEmpty(message="{invalid.docId}")
    private String docId;

    @NotEmpty(message="{invalid.title}")
    @Size(max="{max.default.value}", message="{invalid.title}")
    private String title;
}

I added max.default.value in validation.properties file, but the max can be int and I'm passing String to it. 我在validation.properties文件中添加了max.default.value ,但是最大值可以是int ,我正在将String传递给它。 So as a result: 因此,结果是:

Type mismatch: cannot convert from String to int

Is there any way to achieve this? 有什么办法可以做到这一点?

Just because Sonar whines about something doesn't mean your code is bad. 仅仅因为Sonar抱怨某事并不意味着您的代码很糟糕。

Sonar will already be happy if you put this "magic" value into a private static final at the top of your class. 如果您将此“魔术”值放入班级顶部的private static final ,Sonar将很高兴。 No need to make it a property (I doubt your system would react well if someone decided to change this later on). 无需将其设置为属性(我怀疑如果以后有人决定更改此设置,您的系统会反应良好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM