问题
i created a custom ConstraintValidator
Annotation which called APIAuth
,
and i tried to fetch the remote user IP Address Using @Context HttpServletRequest
, but the problem is when calling the APIAuth
inside my Stateless , the APIAuth
custom validator work , and it fetch the remote user ip address , but when i try to refresh the request again quickly , it throw an exception , because of @Context HttpServletRequest
be null at this case , it need from me to wait some seconds before trying to request the Stateless
Restful again .
my APIAuth
Code :
APIAuth.class
@Documented
@Constraint(validatedBy = APIAuthValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface APIAuth {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
APIAuthValidator.class
public class APIAuthValidator implements ConstraintValidator<APIAuth, String> {
@Context
private HttpServletRequest client;
@Override
public void initialize(APIAuth constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
boolean valid = "127.0.0.1".equals(client.getRemoteAddr());
return valid;
}
Note: i noticed also that when i define the remote user ip address at first inside the initialize() constructor , then it cache the value and didn't update it else after some of seconds , although of refreshing requesting of Restful Stateless API
class which contain the calling of my custom annotation many times.
Thank you,
来源:https://stackoverflow.com/questions/21368583/why-is-an-injected-value-sometimes-null-inside-my-custom-constraintvalidator