[英]multipart max file size validation for multiple routes in a spring boot application
[英]Spring Boot validation: get max size from property file
我有一個 spring 啟動服務器,想在 spring 之前驗證我的值。 使用@Size 驗證我可以設置最大尺寸。 但我想從我的 application.property 文件中獲取這個最大大小。
我已經嘗試通過“@Value(...)”加載這個值,但我不能在“@Size”字段中使用這個值。
@Value("${max.size.in.properties}")
private int MAX_SIZE;
@Size(max = 10)
private String description;
你可以像這個帖子一樣按照 Java 反射https://www.baeldung.com/java-reflection-change-annotation-params
這是不可能的,因為注釋需要常量表達式( static final
)並且@Value
不能用於將值注入靜態 final 字段。
也許這個項目可以幫到你: https : //github.com/jirutka/validator-spring 。 它允許您將 Spring 表達式語言與 bean 驗證一起使用。
我們可以使用 Hibernate Validator 以編程方式指定約束,當使用spring-boot-starter-web
時,它已經在類路徑中可用。
鑒於:
class MyObject {
private String description;
...
}
我們可以這樣設置約束:
@Value("${max.size.in.properties}")
private int MAX_SIZE;
HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping.type( MyObject.class )
.property( "description", FIELD )
.constraint( new SizeDef().min( 1 ).max( MAX_SIZE ) );
並使用以下方法驗證對象的實例:
Validator validator = configuration.addMapping( constraintMapping )
.buildValidatorFactory()
.getValidator();
Set<ConstraintViolation<MyObject>> constraintViolations =
validator.validate( myObjectInstance );
if (constraintViolations.size() > 0) {
... // handle constraint violations
}
壞消息:Java Validation API 的標准注釋無法滿足您的需求。
好消息:您可以輕松地創建一個完全符合您要求的自定義注釋。
您需要創建一個自定義驗證注釋(我們稱之為@ConfigurableSize
),它將兩個字符串作為參數,一個是包含最小大小的屬性的名稱,另一個是包含最大大小的屬性的名稱。
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(ConfigurableSize.List.class)
@Constraint(validatedBy = {ConfigurableSizeCharSequenceValidator.class})
public @interface ConfigurableSize {
String message() default "size is not valid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String minProperty() default "";
String maxProperty() default "";
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@interface List {
ConfigurableSize[] value();
}
}
驗證器將在初始化時檢索屬性值,然后將執行與@Size
約束完全相同的驗證檢查。 即使違反約束也會有完全相同的消息。 請注意,如果省略屬性名稱,則min
和max
將分別默認為0
和Integer.MAX_VALUE
,即@Size
默認值相同。
public class ConfigurableSizeCharSequenceValidator implements ConstraintValidator<ConfigurableSize, CharSequence> {
private final PropertyResolver propertyResolver;
private int min;
private int max;
@Autowired
public ConfigurableSizeCharSequenceValidator(PropertyResolver propertyResolver) {
this.propertyResolver = propertyResolver;
}
@Override
public void initialize(ConfigurableSize configurableSize) {
String minProperty = configurableSize.minProperty();
String maxProperty = configurableSize.maxProperty();
this.min = "".equals(minProperty) ? 0 :
propertyResolver.getRequiredProperty(minProperty, Integer.class);
this.max = "".equals(maxProperty) ? Integer.MAX_VALUE :
propertyResolver.getRequiredProperty(maxProperty, Integer.class);
validateParameters();
}
private void validateParameters() {
if (this.min < 0) {
throw new IllegalArgumentException("The min parameter cannot be negative.");
} else if (this.max < 0) {
throw new IllegalArgumentException("The max parameter cannot be negative.");
} else if (this.max < this.min) {
throw new IllegalArgumentException("The length cannot be negative.");
}
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
if (value == null) {
return true;
} else {
int length = value.length();
boolean retVal = length >= this.min && length <= this.max;
if (!retVal) {
HibernateConstraintValidatorContext hibernateContext =
context.unwrap(HibernateConstraintValidatorContext.class);
hibernateContext.addMessageParameter("min", this.min)
.addMessageParameter("max", this.max);
hibernateContext.disableDefaultConstraintViolation();
hibernateContext
.buildConstraintViolationWithTemplate("{javax.validation.constraints.Size.message}")
.addConstraintViolation();
}
return retVal;
}
}
}
您在 bean 中應用自定義注釋
public class SomeBean {
@ConfigurableSize(maxProperty = "max.size.in.properties")
private String description;
}
最后在application.properties
定義屬性
max.size.in.properties=10
就是這樣。 您可以在此博客文章中找到更多詳細信息和完整示例: https : //codemadeclear.com/index.php/2021/03/22/easily-configure-validators-via-properties-in-a-spring-boot-項目/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.