简体   繁体   中英

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

I'm using Hibernate Validator Version 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 ). 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. 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 will already be happy if you put this "magic" value into a private static final at the top of your class. No need to make it a property (I doubt your system would react well if someone decided to change this later on).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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