Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在SpringMVC中从自定义验证器的属性文件中读取参数值_Java_Spring_Spring Mvc - Fatal编程技术网

Java 如何在SpringMVC中从自定义验证器的属性文件中读取参数值

Java 如何在SpringMVC中从自定义验证器的属性文件中读取参数值,java,spring,spring-mvc,Java,Spring,Spring Mvc,我为firstname创建了自定义验证器注释,如下所示: public class ProfileBean { @FirstNameValidator(minLength = 2L, maxLength = 10L, pattern = "firstname_pattern}",channelId="abcd") private String firstName; } ProfileBean是我的POJO,在自定义注释中,我想从属性文件中读取minLength、maxLeng

我为firstname创建了自定义验证器注释,如下所示:

public class ProfileBean {

    @FirstNameValidator(minLength = 2L, maxLength = 10L, pattern = "firstname_pattern}",channelId="abcd")
    private String firstName;
}
ProfileBean是我的POJO,在自定义注释中,我想从属性文件中读取minLength、maxLength和pattern值。我该怎么做

我还有一个问题,我必须支持不同的渠道。对于所有这些通道,bean将不同,但给定字段的注释如下所示: 渠道1: 公共类ProfileBean{

    @FirstNameValidator(minLength = 5L, maxLength = 100L, pattern = "[A-Za-z]{5,100}",channelId="abcd")
    private String firstName;
}
渠道2: 公共类注册bean{

    @FirstNameValidator(minLength = 2L, maxLength = 10L, pattern = "[A-Za-z]{2,10}}",channelId="xyz")
    private String foreName;
}
在本例中,验证实现是相同的,但可能是不同通道的参数值可能不同。在本例中,在实现中,我们如何基于通道加载不同的属性。
在我的例子中,我已经用xml定义了消息bean,并且通过使用该bean的实例,我必须读取属性值。

您不能在ProfileBean中直接这样做,因为传递到注释值的所有内容都必须是常量表达式。您可以做的是

public @interface FirstNameValidator {

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

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

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

    ...

}
在自定义验证器的初始化方法实现中

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())));

    }

    ...
}
并在ProfileBean中注释如下

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

    minLength.get() 

    ...

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