以下是我提出的代码(根据 Ajinkya 和 Alex 的建议):
自定义注释:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy=HomePageEmptyMessageValidator.class)
public @interface HomePageEmptyMessage {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义验证器:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class HomePageEmptyMessageValidator implements ConstraintValidator<HomePageEmptyMessage, EmergencyMessages> {
@Override
public void initialize(HomePageEmptyMessage homePageEmptyMessage) {
}
@Override
public boolean isValid(EmergencyMessages emergencyMessages, ConstraintValidatorContext context) {
if (emergencyMessages == null) {
return false;
}
Integer messageEnabled = emergencyMessages.getMessagesEnabled();
if (messageEnabled != null) {
if (messageEnabled == 1) {
String homePageMessage = emergencyMessages.getHomePageMessage();
if (Util.isNullOrEmpty(homePageMessage)) {
return false;
} else {
return true;
}
} else {
return true;
}
}
return false;
}
}
代码中自定义注解的用法:
@Entity
@Table(name="emergency_messages")
@HomePageEmptyMessage(message="Home page annoucement cannot be empty if the Display Announcement is set to Yes")
public class EmergencyMessages implements Serializable {
private static final long serialVersionUID = -7870767517772161300L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id", nullable=false)
private Integer id;
@Column(name="home_page_message")
private String homePageMessage;
@Range(min=0, max=1, message="Please select one of the display announcement value")
@Column(name="messages_enabled")
private Integer messagesEnabled;
}
我希望它可以帮助某人。