我最近开始研究自定义注释。我创建了一个示例Spring启动项目,它可以正常工作,但是当我尝试与项目代码集成时,验证类没有被调用。
ValidateField.java
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;
@Documented
@Target(value = { ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Constraint(validatedBy = { RequestDataValidator.class })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface ValidateField {
String message() default "invalid or value not present";
int revision() default 1;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
RequestDataValidator.java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class RequestDataValidator implements ConstraintValidator<ValidateField, String>{
@Override
public void initialize(ValidateField constraintAnnotation) {
System.out.println("in Initialize method");
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("in Initialize method");
return (value != null && !value.isEmpty());
}
}
控制器类如下。 请注意@Valid注释与@RequestBody
一起使用import javax.validation.Valid;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.web.bind.annotation.RequestBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Api
@Produces({MediaType.APPLICATION_JSON})
@Path("/service")
public interface UIController {
@POST
@Path("/getRules")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(
value = "Respond Hello <name>!",
response = Response.class
)
@ApiResponses(
value = {
@ApiResponse(code = 404, message = "Service not available"),
@ApiResponse(code = 500, message = "Unexpected Runtime error")
})
public Response getRules(@Valid@RequestBody SampleRequest discountPromoDetailsRequest);
}
我已检查注释是否应用于该字段。事实证明它确实如此。我使用
检查了它field.getDeclaredAnnotations()
SampleRequest.java
public class SampleRequest {
private String name;
@ValidateField
private String lastName;
private Long phNum;
private String address;
.
.
//getters and setters of the same.
}
我现在不确定是什么原因导致RequestDataValidator没有被调用。
我在过去的3天里正在研究这个问题,但我仍然没有在项目中工作。
非常感谢任何帮助。