【发布时间】: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