I would like to inject my original class to my customizing validator without JavaEE environment. I wrote a code for this considering the following points (#1 and #2) according to your reference guide, but I couldn’t get the instance injection (I got a NullPointerException in the isValid call).
How can I get the injection of UserServiceImpl.class, successfully?
Supposedly, ‘org.hibernate.validator.cdi.HibernateValidator’ should be used in somewhere else in the source code.
If my understanding is correct, please let me know how to use it in my codes.
#1. I added the Maven dependency to my POM as shown in Example1.3 in the reference guide.
#2. I prepared validator class and injection class as follows:
Code:
package xxxxx.constraints.impl;
import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import xxxxx.constraints.UnusedUserId;
import xxxxx.service.user.UserServiceImpl;
public class UnusedUserIdValidator implements ConstraintValidator<UnusedUserId, String> {
@Inject
UserServiceImpl userInformation;
@Override
public void initialize(UnusedUserId constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return userInformation.isUnusedUserId(value);
}
}
Code:
package xxxxx.service.user;
public interface UserService {
boolean isUnusedUserId(String userId);
// other methods
}
Code:
package xxxxx.service.user;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class UserServiceImpl implements UserService {
@Override
public boolean isUnusedUserId(String userId) {
// some logics
}
}