我正在为作为@RestController
方法中参数的bean编写测试。Bean POJO:
public class AddTownRequestBean
{
@NotEmpty(message = "INVALID_REQUEST")
@Length(min = 1, max = 30, message = "PARAMETER_OUT_OF_BOUNDS")
private String name;
@NotEmpty(message = "INVALID_REQUEST")
@Length(min = 3, max = 4, message = "PARAMETER_OUT_OF_BOUNDS")
private String typeCreated;
@DateTimeFormat(pattern = "yyyy-MM-dd") //style = "S-", iso = DateTimeFormat.ISO.DATE,
private String foundationDate;
getters and setters...
}
我的问题与@DateTimeFormat
注释有关。在documentation中声明此注释:
可以应用于java.util.Date,java.util.Calendar,Long(毫秒级时间戳)以及JSR-310 java.time和Joda-Time值类型。
正如可以看到的,不支持简单的String
类型,但是我的POJO的日期字段是String
。我已经使用上面概述的@DateTimeFormat
进行了测试,并且带有注释的参数,每次都互斥。而且显然没有解决。
所以问题本身-是否有任何注释或类似的解决方法,可以在要表示日期的String
类型变量中为特定的日期格式添加(使我们称之为)“验证器”?
此问题或类似的问题先前曾被问及回答。以下是上一个问题的链接。请查看该答案是否对您有帮助。
您可以在这种情况下创建自定义验证程序注释。范例
DateTimeValid.class
@Constraint(validatedBy = DateTimeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DateTimeValid{
public String message() default "Invalid datetime!";
public String fomart() default "MM/dd/yyyy";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
}
DateTimeValidator.class
public class DateTimeValidator implements ConstraintValidator<DateTimeValid, String> {
private String dateFormat;
@Override
public void initialize(DateTimeValid constraintAnnotation) {
dateFormat = constraintAnnotation.fomart();
}
@Override
public boolean isValid(String strDate, ConstraintValidatorContext context) {
try {
DateFormat sdf = new SimpleDateFormat(this.dateFormat);
sdf.setLenient(false);
sdf.parse(strDate);
} catch (Exception e) {
return false;
}
return true;
}
}
用法
@DateTimeValid(fomart="...", message="...")
private String foundationDate;
编辑:@Ramu:我之前完成的项目中的这段代码。但是,是的,我阅读了链接,上面的代码也是如此