简体   繁体   中英

How to read arguments value from property file in custom validator in Spring MVC

I have created custom validator annotation for firstname as follows:

public class ProfileBean {

    @FirstNameValidator(minLength = 2L, maxLength = 10L, pattern = "firstname_pattern}",channelId="abcd")
    private String firstName;
}

ProfileBean is my POJO and in custom annotation I want to read minLength , maxLength and pattern value from properties file. How can I do this?

I have one more problem I have to support different channels. For all these channels beans will be different but annotations for given fields are same as follows: Channel1: public class ProfileBean {

    @FirstNameValidator(minLength = 5L, maxLength = 100L, pattern = "[A-Za-z]{5,100}",channelId="abcd")
    private String firstName;
}

Channel2: public class RegisterBean {

    @FirstNameValidator(minLength = 2L, maxLength = 10L, pattern = "[A-Za-z]{2,10}}",channelId="xyz")
    private String foreName;
}

In this case validation implementation is same, but it might be a case that argument value can be different for different channels. In this case in implementation how can we load different properties based on channels. In my case I have defined message bean in xml and and by using instance of that bean I have to read property value.

You can't directly do it in your ProfileBean as everything passed into Annotation value must be Constant Expressions. What you can do is

public @interface FirstNameValidator {

    public String minLengthProp() default "min.length";

    public String maxLengthProp() default "max.length";

    public String patternProp() default "min.length";

    ...

}

And in your Custom Validator's initialize method implementation

private Properties properties ... // Load properties

private ThreadLocal<Integer> maxLength = new ThreadLocal<Integer>();
private ThreadLocal<Integer> minLength = new ThreadLocal<Integer>();
private ThreadLocal<String> pattern = new ThreadLocal<String>();

@Override
public void initialize(FirstNameValidator firstNameValidator) {
    if(firstNameValidator.minLength() == null) {
        minLength.set(Integer.parseInt(properties.getProperty(firstNameValidator.minLengthProp())));

    }

    ...
}

And in your isValid method

@Override
public boolean isValid(User user,
        ConstraintValidatorContext constraintValidatorContext) {

    minLength.get() 

    ...

}

And Annotate as following in your ProfileBean

@FirstNameValidator(minLengthProp = "name.minLength", maxLengthProp = "name.maxLength", patternProp = "name.pattern")

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