我们被要求更换一些软件。目前,需要替换的东西之一是Hibernate。他们希望直接使用JPA,因此很容易从Hibernate切换到openJPA,然后切换到…。
所使用的注释之一是:
@NotEmpty(message = "Field is not filled")
与进口有关:
import org.hibernate.validator.constraints.NotEmpty;
我的大学想用:
@NotNull(message = "Field is not filled")
@Size(message = "Field is not filled", min = 1)
我不喜欢这样。当然不是干的。(它被使用了数百次。)我更喜欢定义我们自己的NotEmpty。但我从来没有处理过注释。怎么做?
-目前的解决办法:
重新命名了这个函数,因为将来它可能会被扩展。
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.ReportAsSingleViolation;
@Documented
@Constraint(validatedBy = { })
@Target({ FIELD })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface CheckInput {
public abstract String message() default "Field is not filled";
public abstract String[] groups() default { };
}
发布于 2015-07-11 03:06:03
查看@NotEmpty源代码-实际上它只封装了验证器@NotNull和@Size(min=1)。
您只需创建您自己的类,其外观与Hibernate Validator的@NotEmpty完全相同:
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
/**
* Defines several {@code @NotEmpty} annotations on the same element.
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface List {
NotEmpty[] value();
}
}
https://stackoverflow.com/questions/31347663
复制