【问题标题】:How to get the value of the @Size annotation, above the field of object如何获取对象字段上方的@Size注释的值
【发布时间】:2019-10-10 19:25:15
【问题描述】:

我需要从 @Size 注释中提取属性值

private static int getMaxLimitSize(Field field){

    field.setAccessible(true);
    Size annotation = field.getAnnotation(Size.class);

    int zero = 0;

    if(annotation == null) return zero;

    return annotation.max();

}

这里是对 dto 类型对象字段的 @Size 约束

 @Size(message = "{validate.documentid.size}", max = 36)
private String documentId;

但是当我尝试获取注释时,我得到 null

Size annotation = null;

这个注解在dto类型的对象之上并且没有被处理,但是当entity被处理时,那么这个注解是可见的?!!!

使用 Spring Boot

错误 messages 在文件中 - ValidationMessages.properties

@Configuration
public class ServiceConfig implements WebMvcConfigurer {



    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setDefaultEncoding("UTF-8");
        source.setBasename("classpath:ValidationMessages");
        return source;
    }

    @Nullable
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

}

这是方法中传递的内容 - getMaxLimitSize(),输入字段

private static void processLimitValidateForField(Field field, Object object, List<Object> values){

    Class<?> type = field.getType();
    String typeName = type.getSimpleName();

    boolean isTypeClassOfString = isStringType(typeName);

    int limitString = 0;

    if(isTypeClassOfString){
        limitString = getMaxLimitSize(field);
        setValue(field, typeName, object, values, limitString);
    } else {
        setValue(field, typeName, object, values, limitString);
    }
}

请解释为什么 dto 对象对验证器不可见,或者为什么反射看不到 validate 注解以及可以做什么?

如何解决这个问题?

【问题讨论】:

    标签: hibernate spring-boot reflection bean-validation dto


    【解决方案1】:

    可以通过调用Field#get(currentObject)方法获得field value

    if (field.isAccessible()) {
        Object someValue = field.get(object);
    }
    

    【讨论】:

    • 我必须这样做吗?我传递了一个对象,我试图获取一个对象,但我得到了 null。
    • object 是谁拥有你想要获取其值 JIC 的字段。
    • ?你想做什么?
    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 2017-09-28
    • 2017-12-18
    • 2023-04-03
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    相关资源
    最近更新 更多